【问题标题】:KnockoutJS: How to run script after inserting data in observable arrayKnockoutJS:如何在可观察数组中插入数据后运行脚本
【发布时间】:2013-01-18 12:45:30
【问题描述】:

我有一个画廊列表:

 <div class="gallery">
            <a href="#" class="next">next</a>
            <a href="#" class="prev">prev</a>

            <div class="frame">
                <ul data-bind="foreach: designs">
                    <li>
                        <span class="text">№<span data-bind="text: getID()"></span> <span data-bind="text: getName()"></span></span>
                         <img src="images/img01.jpg" width="182" height="102" alt="image description"/>
                    </li>
                </ul>
            </div>

  </div>

JS

Models.Design = function () {...}

function ViewModel(){   
    this.designs = ko.observableArray();


    this.addDesign = function (_id, _name, _image, _video) {

        var design = new Models.Design;

        design.setID(_id);
        design.setName(_name);

        this.designs.push(design);
   };

   this.addDesign(1, "Image 1");
   this.addDesign(2, "Image 1");
   this.addDesign(3, "Image 1");
 // at this moment there is no elements in DOM
}

问题:我需要在哪里写$('.gallery').galleryScroll(); 来更新我的画廊滑块?

【问题讨论】:

    标签: javascript data-binding knockout.js knockout-2.0


    【解决方案1】:

    只需订阅 observable。集合的任何可见*更改都会调用您的回调。

    function ViewModel() {
        this.designs = ko.observableArray();
        this.designs.subscribe(function () {
            $('.gallery').galleryScroll();
        });
    
        // ...
    }
    

    * 可见意味着你对 observable 执行操作,而不是直接对底层数组执行操作。

    【讨论】:

      【解决方案2】:

      我找到了解决办法:

      ko.bindingHandlers.gallery = {
          update: function(element, valueAccessor) {
              setTimeout(function() {
                  $(element).parents('.gallery').galleryScroll();
              });
          }
      };
      
       <ul data-bind="foreach: designs, gallery:{}">
           <li>....</li>
       </ul>
      

      【讨论】:

        猜你喜欢
        • 2012-04-20
        • 1970-01-01
        • 2017-11-25
        • 2015-11-30
        • 2018-08-04
        • 2013-12-16
        • 2013-05-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多