简体   繁体   English

使用文字符号在名称空间中扩展对象

[英]Extend object in namespace using literal notation

I have a page that contains a bunch of elements like inputs and select boxes that individually need functions added to them that control their specific behaviour. 我有一个页面,其中包含许多元素,例如输入和选择框,这些元素需要分别添加控制其特定行为的功能。

My code is currently: 我的代码当前为:

var mpp_ui = {
    itemList : document.getElementById('mpp_itemlist')
};

mpp_ui.itemList.clear = function(){
    while(this.length > 0){
        this.remove(0);
    }
};

Where mpp_ui is used as a namespace that contains all the elements that need functions assigned to them and mpp_ui.itemList is a HTML select element. 其中mpp_ui用作命名空间,其中包含需要mpp_ui.itemList分配功能的所有元素,而mpp_ui.itemList是HTML select元素。

If at all possible I want to avoid having to type mpp_ui in every function statement. 如果有可能,我希望避免在每个函数语句中都键入mpp_ui。 I would like to declare the functions like this (partially pseudo-code because I don't quite know how to go about it): 我想声明这样的功能(部分伪代码,因为我不太了解如何处理):

var mpp_ui = {
    itemList : {
        DEFINE IT AS document.getElementById('mpp_itemlist').
        Then extend it with functions like so:
        clear : function(){
            while(this.length > 0){
                this.remove(0);
            }
        }
    }
}

Or alternatively, if above isn't possible: 或者,如果以上操作不可行:

var mpp_ui = {
    itemList : document.getElementById('mpp_itemlist'),
    itemList.clear : function(){
        while(this.length > 0){
            this.remove(0);
        }
    }
}

The last code is the first thing I tried, but it gives me a SyntaxError: Unexpected token . 最后的代码是我尝试的第一件事,但是它给了我SyntaxError: Unexpected token . on the line where itemList.clear is defined. 在定义itemList.clear的行上。

After digging trough many options, the closest I've gotten to my desired format is by declaring the elements in the namespace and then extending them with the desired functions, for which I use underscore.js . 在挖掘了很多选项之后,最接近所需格式的方法是在名称空间中声明元素,然后使用所需函数扩展它们,为此我使用了underscore.js The result: 结果:

mpp_ui = {
    itemList : document.getElementById('mpp_itemlist')
};
_(mpp_ui.itemList).extend({
    clear : function(){
        while(this.length > 0){
            this.remove(0);
        }
    }
});

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

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