Mirroring foreach with template in a custom binding

57 views
Skip to first unread message

and...@wimpyprogrammer.com

unread,
Apr 22, 2013, 12:05:50 AM4/22/13
to knock...@googlegroups.com
I am new to KnockoutJS and trying to create a custom binding that mirrors the behavior of foreach.  Then I will add my custom logic, but I'm stumbling on these initial steps.  Ultimately I would like to build a custom binding for jQuery Quicksand (http://razorjack.net/quicksand/).

I've created an example at http://jsfiddle.net/wimpyprogrammer/N6NaC/.

My custom binding doesn't work when referenced in a template.  My understanding from the foreach binding source is that approaches #1, #2, and #5 should be equivalent but #5 doesn't work.  If approach #4 doesn't work then I'm not surprised that #6 doesn't; it was just a stab in the dark.

What do I need to do to make my custom binding work with templates?

Michael Best

unread,
Apr 22, 2013, 4:55:01 PM4/22/13
to knock...@googlegroups.com, and...@wimpyprogrammer.com
The foreach binding is separate from the template binding, although it's currently implemented to use the latter. In your examples, only the first two are using your custom binding. If you wanted to add a new option to the template binding, you'd have to replace the template binding handler as well.

-- Michael

and...@wimpyprogrammer.com

unread,
Apr 23, 2013, 6:10:18 PM4/23/13
to knock...@googlegroups.com, and...@wimpyprogrammer.com
Thanks Michael, that hadn't occurred to me.  I was able to mirror the template binding in the same fashion.  In case someone else is attempting the same, here are my custom bindings.

ko.bindingHandlers.myforeach = {
    init
: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
       
return ko.bindingHandlers['foreach']['init'](element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
   
},
    update
: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
       
return ko.bindingHandlers['foreach']['update'](element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
   
}
};
ko
.bindingHandlers.mytemplate = {
    init
: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
       
return ko.bindingHandlers['template']['init'](element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
   
},
    update
: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
       
return ko.bindingHandlers['template']['update'](element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
   
}
};

This allows me to use the following data-binds:

myforeach: people
myforeach: { data: people }
mytemplate: { name: 'template-id', foreach: people }

But the following does not work:

mytemplate: { name: 'template-id', myforeach: people }

Just an FYI for others.
Reply all
Reply to author
Forward
0 new messages