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:

  • to prevent global variable leaks such as var foo = bar; (after which window.foo === foo)
  • to prevent the 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
      the second one is shorter but is often not preffered because one can simple overwrite the undefined variable's value : undefined = 13;.
      By not proviiding an actual value for the undefined argument in the iife, you're actually resetting the undefined variable to undefined.
  • to generalize the global object
    • some say that the access to the global variable is faster than to the window object due to the fact that the js engine first looks into the lower scope
    • if you're running the code in a different environment than the browser and you have calls to the 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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top