2017-03-01 68 views
2

我想創建一個與BDD(行爲驅動開發)的jQuery模塊。應該jquery組件返回false

這裏是我的組件

(function($) { 
    function MyModule(element){ 
     return false;   
    } 

    $.fn.myModule = function() { 
     var args = Array.prototype.slice.call(arguments, 1); 
     return this.each(function() { 
      new MyModule(this); 
     }); 
    }; 

    $.fn.myModule.Constructor = MyModule; 

})(window.jQuery); 

這裏是我的測試

QUnit.test("test", function(assert) { 
    assert.expect(1); 

    var smallBox = $('<div/>',{'id':'smallBox'}).width(200).height(200); 
    var result = smallBox.myModule(); 
    console.log(result); // This gives the HTML element itself but I am expecting it must be boolean false 
    assert.notOk(result, "should return false"); 
}); 

HERE IS FIDDLE

我有2個問題。

1-如果我的組件返回布爾值,該怎麼辦?它是錯誤的模式?

2-如何我可以從我的組件

回答

1

那是因爲你沒有返回new MyModule返回布爾,你回來的this.each返回的值是一個jQuery對象。如果你想要一個布爾值,你必須返回一個布爾值。就像這樣:

$.fn.myModule = function() { 
    var args = Array.prototype.slice.call(arguments, 1); 

    this.each(function() { // don't return here because then you'll return a jQuery object 
     new MyModule(this); 
    }); 

    return false;   // return a boolean (works) 
}; 

從回調中返回是不影響父函數的返回值。

+0

所以驗證應該在$ .fn.myModule內 –

+0

@MehmetErenYener是的,你應該積累所有'新的MyModule'調用的結果,然後返回該值。 –

相關問題