2
關閉過的細微差別

我一直在試圖理解JavaScript的功能組成的技術和我想出了一個玩具準MVC他的工作代碼來說明我的問題:在Javascript

var modelFactory = function() { 
 
    var _state = false; 
 
    var _listener = null; 
 

 
    var _updateView = function() { 
 
    _listener(_state); 
 
    }; 
 

 
    var _interface = { 
 
    registerListener: function(listen) { 
 
     _listener = listen; 
 
    }, 
 
    eventHandler: function() { 
 
     _state = true; 
 
     _updateView(); 
 
    } 
 
    }; 
 
    return _interface; 
 
}; 
 

 
var viewFactory = function(updateFunction) { 
 
    var _hook = $('<div class="box"></div>'); 
 
    $('body').append(_hook); 
 

 
    var _interface = { 
 
    getHook: function getHook() { 
 
     return _hook; 
 
    }, 
 
    update: updateFunction(_hook) 
 
    }; 
 

 
    return _interface; 
 
}; 
 

 

 
var main = function() { 
 

 
    var modelInstance = modelFactory(); 
 

 
    var viewInstance = viewFactory(
 
    function bindHook (hook) { 
 
     return function bindState (state) { 
 
     if (state === true) { 
 
      hook.addClass("red"); 
 
     } else { 
 
      hook.removeClass("red"); 
 
     } 
 
     }; 
 
    } 
 
); 
 

 
    modelInstance.registerListener(viewInstance.update); 
 
    modelInstance.eventHandler(); // When called, mutates _state, then calls the listener 
 
}; 
 

 
$(document).ready(main);
.box { 
 
    background-color: #000; 
 
    width: 100px; 
 
    height: 100px; 
 
} 
 
.red { 
 
    background-color: #f00; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

在此代碼我傳遞在結合的「鉤」的變量,並且返回其範圍保留了結合的功能的功能。這是我的問題的關鍵。

我希望能夠抽象出來的「鉤子」的結合,這樣我就可以通過在「狀態」功能結合到一個函數,然後做「鉤子」的結合。我還沒有想出如何使用Javascript提供的後期綁定工具來執行此操作(應用/調用此方法)。我可以傳遞對象引用來保持狀態,並且完成任務,但是我更感興趣的是解決這個問題的更多功能方法。所以:

一)有沒有辦法做我想在JavaScript中基本的封鎖做,如果是的話怎麼樣,或者

b)若我應該使用後期綁定「這個」爲本方法,最好的方法是什麼?我假設這是在Javascript中泛化函數狀態的嘗試和真實的方式,但是我正在編寫的代碼這樣做最終沒用。

+0

萬歲!有人誰麻煩構建一箇中途體面的問題。 – 2015-01-21 03:31:26

+1

對不起,你在說什麼「掛起」變量? – Bergi 2015-01-21 03:32:49

+0

對不起!我的意思是鉤。這個例子是從一個在掛鉤上使用掛起方法的程序中提取的。我很困惑 - 編輯很快。 – AveryIsDasein 2015-01-21 04:51:01

回答

0

我想你只是想把封閉的創作您的viewFactory

​​

創建這種封閉只是partial application的情況下,這當然可以在一個輔助功能被抽象出來(以被稱爲update: partial(updateFunction, _hook))。

您也可以使用bind作爲該函數的一個局部應用程序this綁定。假設你想通過掛鉤爲this,你要麼寫

update: function(state) { 
    return updateFunction.call(_hook, state); // notice the similarity to above 
} 

或只是(等效)

update: updateFunction.bind(_hook)