Mixing Knockout with jQuery

我的未来我决定 提交于 2019-12-12 12:07:31

问题


I'm creating a commenting system with knockout.js and I'm having some issues with getting the templating working with our existing jQuery functions.

One example is with the dates comments are created. I wrote a jQuery function that causes the data to turn from 5-5-2012 to 2 Days ago. For example:

    <ul data-bind="foreach: Comments">
        <li data-bind="attr: { id: Id }" class="Comment">
           <div data-bind="text: DateCreated" class="prettyDate"></div>
           ...
        </li>
    </ul>


    <script type="text/javascript">
          $(function(){
              $(".prettyDate").prettify();
          });
    </script>

With this code, when I add a new comment dynamically, the date stays in the 5-5-2012 format. There are several other custom jQuery functions that act on repeating data that is now dynamically created by knockout (usually by selecting based on classes).

How can I apply these custom jQuery functions on dynamic data generated by knockout.js?


回答1:


One option might be to use a custom binding handler which sends bound elements through your jQuery plugin, e.g.:

http://jsfiddle.net/mikebridge/Q9r86/4/

Another possibility might be to add a computed observable in your view model.




回答2:


If you need to run some further custom logic on the generated DOM elements, you can use any of the afterRender/afterAdd/beforeRemove/beforeMove/afterMove callbacks described below.

<ul data-bind="foreach: { data: myItems, afterAdd: yellowFadeIn }">
    <li data-bind="text: $data"></li>
</ul>
<button data-bind="click: addItem">Add</button>


<script type="text/javascript">
    ko.applyBindings({
        myItems: ko.observableArray([ 'A', 'B', 'C' ]),
        yellowFadeIn: function(element, index, data) {
            $(element).filter("li")
                      .animate({ backgroundColor: 'yellow' }, 200)
                      .animate({ backgroundColor: 'white' }, 800);
        },
        addItem: function() { this.myItems.push('New item'); }
    });
</script>

Source: http://knockoutjs.com/documentation/foreach-binding.html#note-7-post-processing-or-animating-the-generated-dom-elements

However, beware of the following note:

If your goal is actually to attach other behaviors to new DOM elements when they have been added (e.g., event handlers, or to activate third-party UI controls), then your work will be much easier if you implement that new behavior as a custom binding instead



来源:https://stackoverflow.com/questions/10508916/mixing-knockout-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!