开发者

jQuery Call within JavaScript class instances leads to last instance

I have problem with two classes and a jquery call. Unfortunatly if a call a method in one class it thinks it is the other one.

Here in detail:

I am writing a form, where the user can write down two customer numbers in two different input fields. The website will query each customernumber via jQuery AJAX and display details from the customer numbers.

So I wrote a class for not duplicating the code and assigning the behaviour to each input field.

CustomerData = function(settings){
    this.name = '';        
    this.street = '';
    this.zipcode ='';
    this.town = '';
    this.inputField = settings.inputfield;
    this.init();
}
CustomerData.prototype.init = function() {
    this.associateClassWithUi();
}

//here I assign the class with the inputfield via jQuery
CustomerData.prototype.associateClassWithUi = function() {
    _this = this;
    console.log("associate " +this.inputField);
    $(this.inputField).focus(function() {
        console.log(' focus on '+_this.inputField);
    });
    $(this.inputField).blur(function() {
        customerId = $(this).val();
        console.log("blur event " + _this.inputField);
        if(customerId != ''){
            _this.main(customerId);
        } else {
            _this.setEmpty();
            _this.propertiesToUi();   
        }
    });
}

I am defining the classes this way:

var DataCustomer1 = new CustomerData({
    inputField: '#customer1'
});

var DataCustomer2 = new CustomerData({
    inputField: '#customer2'
});

console.log gives me the following:

associate #customer1
associate #customer2

But clicking on the input fields (#customer1 and #customer2) I always get this

focus on #customer2
focus on #customer2
focus on #customer2

Of course if I change the order of instantiation

var DataCustomer2 = new CustomerData(...);
var DataCustomer1 = new CustomerData(...);

each of them thinks he is customer1

What am I missing? 开发者_如何学JAVA


Use var _this = this; otherwise it is being declared globally and overwritten each time.


When you declare a variable without var then it always becomes global. If you have this HTML:

<ul>
    <li id="customer1">Customer 1</li>
    <li id="customer2">Customer 2</li>
</ul>

The following code works as expected:

CustomerData = function(settings){
    this.inputField = settings.inputField;
    this.init();
}
CustomerData.prototype.init = function() {
    this.associateClassWithUi();
}

CustomerData.prototype.associateClassWithUi = function() {
    var _this = this;
    console.log("associate " +this.inputField);
    $(this.inputField).click(function() {
        console.log('click on '+_this.inputField);
    });
}

var DataCustomer1 = new CustomerData({
    inputField: '#customer1'
});

var DataCustomer2 = new CustomerData({
    inputField: '#customer2'
});

You can find more information about JavaScripts variables here

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜