3

I saw a Javascript MVC article here, and the model is defined as:

var ListModel = function (items) {
    this._items = items;
    this._selectedIndex = -1;

    this.itemAdded = new Event(this);
    this.itemRemoved = new Event(this);
    this.selectedIndexChanged = new Event(this);
};

ListModel.prototype = {

    getItems : function () {
        return [].concat(this._items);
    },

    addItem : function (item) {
        this._items.push(item);
        this.itemAdded.notify({item: item});
    },

    removeItemAt : function (index) {
        var item = this._items[index];
        this._items.splice(index, 1);
        this.itemRemoved.notify({item: item});
        if (index == this._selectedIndex)
            this.setSelectedIndex(-1);
    },

    getSelectedIndex : function () {
        return this._selectedIndex;
    },

    setSelectedIndex : function (index) {
        var previousIndex = this._selectedIndex;
        this._selectedIndex = index;
        this.selectedIndexChanged.notify({previous: previousIndex});
    }

};  

question 1. In Javascript, what does underscore means? e.g. this._items

question 2. in model, where does it use, how to use the following things:

this.itemAdded = new Event(this);
    this.itemRemoved = new Event(this);
    this.selectedIndexChanged = new Event(this);

2 Answers 2

7

The underscore is just convention, it only has meaning to indicate what was in somebodies head when they wrote it. In general people use an underscore to prefix method names that are meant to be private methods, meaning only use internally to a class, not used by other users.

Sign up to request clarification or add additional context in comments.

Comments

1

The underscore doesnt mean anything, you can just use it in your variable names.

In this case it seems to be an indication that its supposed to be used for a private variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.