开发者

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

开发者 https://www.devze.com 2023-02-08 02:31 出处:网络
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

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.


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.


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消