简体   繁体   English

如何使用JavaScript中的括号符号将函数附加到对象?

[英]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. 我正在编写一个JavaScript,该JavaScript应该将上下文菜单附加到文档中的元素。 The jquery plugin for the context menu requires an id of the context menu and an options object. 上下文菜单的jquery插件需要上下文菜单的ID和options对象。 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. 选项对象具有称为绑定的属性,该属性应具有键/值对,其中键是菜单项的ID,值是单击时调用的函数。

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. 问题是我要填充的绑定对象在使用方括号概念时没有将功能附加为值,并且我需要它,因为菜单项的ID无法预先确定。

    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. 那可能只是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. 您没有包括脚本正在处理的HTML,但是我猜测是所选的li元素没有id属性。 As a result, when you assign item.id to key , it's an empty string and thus not a valid property name . 结果,当您将item.id分配给key ,它是一个空字符串 ,因此不是有效的属性名

If you tack an id on each li , it should work just fine: http://jsfiddle.net/8TL7u/ 如果在每个li上添加一个id ,它应该可以正常工作: 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. 它在Chrome中运行,所以我记得我在使用Firefox 4 Beta,所以我刚刚重启了Firefox,它神奇地工作了。 If I could reproduce it again I would be able to provide more details. 如果我可以再次复制它,那么我将能够提供更多细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM