简体   繁体   中英

How to attach functions to objects using the bracket notation in JavaScript?

I'm writing a javascript that is supposed to attach a context menu to an element in the document. The jquery plugin for the context menu requires an id of the context menu and an options object. The options objects has a property called bindings that should have key/value pairs where the key is an id of a menu item and the value is a function invoked upon click.

The problem is that the bindings object that I'm trying to populate doesn't attach functions as values when using bracket notion, and I need it since, the menu items' id's cannot be determined in advance.

    var bindings = {};

    var bindingsFunction = function(t){
        alert('Trigger was ' + t.id + '\nAction was Open');
    };

    var $listItems = $contextMenu.find('li');

    $listItems.each(function(index, item){
        var key = '' + item.id;
        bindings[key] = bindingsFunction;
    });

    console.log('bindings is empty', bindings); 

    var result = $icon.contextMenu(contextMenuId, {
        bindings: bindings
    });

That might be just a "buggy"(?) display from Firebug. Example:

var mytest = {};

var foo = function() {
};

mytest['foo'] = foo;

console.log(mytest);

will display:

Object { }

Looks like an empty object, but if you click on it you'll see the content.

You didn't include the HTML that your script is working on, but my guess is that the li elements that are being selected do not have an id property. As a result, when you assign item.id to key , it's an empty string and thus not a valid property name .

If you tack an id on each li , it should work just fine: http://jsfiddle.net/8TL7u/

It was working in Chrome, so I remembered that I'm working on a Firefox 4 Beta, so I just restarted Firefox and it magically worked. If I could reproduce it again I would be able to provide more details.

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