I have a custom binding handler and want to modify it to IIFE. I have been reading on internet about IIFE but could not able how to change my custom handle into IIFE. So how can I change following binding handler into IIFE
define(['knockout', 'jquery'], function(ko, $) {
ko.bindingHandlers.er = {
init: function(el, va) {
console.log($(el).find('.n').text());
$(el).find('.edit').hide().end().find('.detail').show();
$(el).find('.ebtn').on('click', function() {
$(el).find('.edit, .detail').toggle();
});
$(el).find('.ubtn').on('click', function() {
$(el).find('.edit, .detail').toggle();
});
}
};
});
It's quite unclear what you're asking here :(.
Immediately-Invoked Function Expression (IIFE) is an anonymous function that executes immediately. In your case, if you can't be more specific, it's really hard to guess where do you want to place the iife.
I normally put my whole code into an iife in order to take advantage of the function scope and use it as a closure, thus minimising the global object pollution and it generally looks like this :
(function(global,undefined){
// the code goes here
// global === window
})(this);
In your case, you can do the same :
(function(global,undefined){
define(['knockout','jquery'],function(ko,$){
// ...
});
})(this);
Update :
Here are some explanations for those who need them.
The following pattern is used:
var foo = bar;
(after which window.foo === foo
)undefined
value to get overwritten. Let's say you want to check if something is undefined. you have 2 ways to do it :typeof foo === 'undefined'
foo === undefined
undefined
variable's value : undefined = 13;
.undefined
argument in the iife, you're actually resetting the undefined
variable to undefined.global
variable is faster than to the window
object due to the fact that the js engine first looks into the lower scope window
object, your code might break because the global object is different from environment to ennvironment (adobe pdfs, node js, rhino ... ). This can be solved by remaping the global object to a variable (in our case global
), by reffering it to the this
object from the global scope