这是显示消息的好习惯对象吗?

时间:2011-11-21 22:15:52

标签: javascript

它有效,我已经测试过了。我想知道的是 - 这是一个好习惯。显然我可以使用一个关联数组并调用它。但我想把它封装成一个有状态的物体。

var View_message = function(div)
{    this.messages = 
    {
        empty: 'Please complete all fields',
        empty_bm: 'Please enter both a title and url',
        name: 'Only letters or dashes for the name field',
        email: 'Please enter a valid email',
        same: 'Please make emails equal',
        taken: 'Sorry that email is taken',
        pass: 'Please enter a valid password, 6-40 characters',
        validate: 'Please contact <a class="d" href="mailto:support@archemarks.com">support</a> to reset your password',
        url:  'Pleae enter a valid url'
    }; 
    this.div = div; 
}; 

View_message.prototype.display = function(type) 
{
    document.getElementById(this.div).innerHTML=this.messages[type];
};

obj_view = new View_message('test_id')
obj_view.display('empty');

2 个答案:

答案 0 :(得分:2)

您将为this.messages的每个实例创建View_message的副本。为了防止这种情况,您可以将消息存储在原型中。

此外,每次显示消息时,您都在查找div。我会在构造函数中存储对div的引用。

function View_message (div)
{
    this.div = document.getElementsById(div);
}

View_message.prototype.messages = {
    empty: 'Please complete all fields',
    empty_bm: 'Please enter both a title and url',
    name: 'Only letters or dashes for the name field',
    email: 'Please enter a valid email',
    same: 'Please make emails equal',
    taken: 'Sorry that email is taken',
    pass: 'Please enter a valid password, 6-40 characters',
    validate: 'Please contact <a class="d" href="mailto:support@archemarks.com">support</a> to reset your password',
    url:  'Pleae enter a valid url'
};
View_message.prototype.display = function(type)
{
    this.div.innerHTML = this.messages[type];
};

答案 1 :(得分:1)

你的方式没有任何问题,但除非你有更多与这些错误消息相关的函数,否则为它创建一个原型并为它实例化一个新对象似乎有些过分。您可以在一个函数中实现display方法,该函数将type和id作为参数。

function displayMessage(type, div) {
    var msgs = {
        empty: 'Please complete all fields',
        empty_bm: 'Please enter both a title and url',
        name: 'Only letters or dashes for the name field',
        email: 'Please enter a valid email',
        same: 'Please make emails equal',
        taken: 'Sorry that email is taken',
        pass: 'Please enter a valid password, 6-40 characters',
        validate: 'Please contact <a class="d" href="mailto:support@archemarks.com">support</a> to reset your password',
        url:  'Pleae enter a valid url'
    }; 
    document.getElementById(div).innerHTML = msgs[type];
}

如果你经常调用它,你甚至可以将msgs结构放入一个闭包中,这样每次调用时都不需要对它进行评估。