Skip to content

Instantly share code, notes, and snippets.

@togakangaroo
Created July 30, 2013 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save togakangaroo/6117061 to your computer and use it in GitHub Desktop.
Save togakangaroo/6117061 to your computer and use it in GitHub Desktop.
!function(){
//Initialize a jQuery Ui Widget on this element.
//<button id="click-here" data-bind="widget: {name: 'button' options: 'label:\'Click Here\', disabled: true'}, click: doSomething">Click Here</button>
//will have the same effect as
//<button id="click-here" data-bind="click: doSOmething">Click Here</button>
//<script>$(function(){ $('#click-here').button(label: 'Click Here'), disabled: true })</script>
//In the more common case when options are not needed you may simply write
//<button id="click-here" data-bind="widget: 'button', click: doSomething">Click Here</button>
ko.bindingHandlers.widget = {
init: function(el, valueAccessor){
var val = valueAccessor()
,options = val.options && evaluateJsonishString(val.options)
,widget = val.name || val
,run = val.defer ? defer : doNow
;
run(function(){
if(!(typeof $.fn[widget] == 'function'))
return console.error("No such widget found:", widget);
$(el)[widget](options);
});
}
}
function doNow(fn) { return fn() };
function defer(fn) { setTimout(fn, 0); }
function evaluateJsonishString(str) {
var ctx = {res: null};
with(ctx)
eval('res = {' + str + '}');
return ctx.res;
}
}()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment