简体   繁体   中英

How to stop the multiple binding in KnockOut.js

I have a view model like this :

function ImageViewModel() 
{    
    var self = this;

    self.totalRecordCount = ko.observable();  

    self.currentRecordCount = ko.observable();

    self.images = ko.observableArray();
     // fetching all available images
    getAvailableImages(self, imageGalleryId, 1);//1 is page number for paging
}

I have html as followes:


<div id="available Images" class="available-images" data-bind="foreach:images">
<div c`enter code here`lass="available-image">
<div class="col-sm-4 thumbnail">
<asp:CheckBox ID="cbxImage" runat="server" CssClass="checkbox" />
<img alt="" data-bind="attr: { 'src': ImagePath, id: 'img_' + ImageId, 'data-id': ImageId }"
style="border: none;" />
</div>
</div>
</div>

i have java script at the page bottom as :

  $('.galleryfooter').click(function () {
            $(this).attr('data-target', '#imageModal');
            $(this).attr('data-toggle', 'modal');
            ko.applyBindings(new ImageViewModel(), document.getElementById("imageGallery"));
        });

when i first Clicked the images are bind properly but when i clicked the button again then images are get multiplied.Means if i have 5 images in database it displays 25 images.So what should i do?

Stop using jQuery to handle events. Knockout has bindings for that. The agreement you have with Knockout is that it controls the DOM and you only manipulate the viewmodel.

See the click binding and the attr binding . Also, if you have not gone through the Knockout tutorial , I highly recommend it. It will help you let go of the DOM.

I agree with Roy. You need to separate your concerns better. That is the whole point of having a controller. As it stands with every click you are reapplying the binding. The binding should only be applied once. It should be more like this.

function ImageViewModel() 
{    
    var self = this;

    self.totalRecordCount = ko.observable();  

    self.currentRecordCount = ko.observable();

    self.images = ko.observableArray();
    // fetching all available images
    getAvailableImages(self, imageGalleryId, 1);//1 is page number for paging

    this.clickThis = function()
    {
        //doStuff
    };
}

ko.applyBindings(new ImageViewModel(), document.getElementById("imageGallery"));

I don't know where your gallery footer is supposed to go. But here is a guess.

<div class="galleryfooter" data-bind="click: function(e){$root.clickThis();}"></div>

Also use knockout for attribute binds instead of jquery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM