簡體   English   中英

在 Javascript 上實現事件的最佳方法

[英]Best way to implement Events on Javascript

作為 .NET 開發人員,我習慣於自定義控件上的委托和事件。 我一直在創建 javascript 代碼很長一段時間,但我想知道在 javascript 中實現它的最佳方法。 下面是我通常如何編碼我的組件。

var RGComp= RGComp || {};
RGComp.MyComponent = function () {
    function events(){
        $("a").unbind("click");
        $("a").click(function () {
             // Do something
        });
    }
    function generateUI(){
        //generate HTML UI
        events();
    }
}

我確定這是不恰當的。 我必須一直調用 unbind 以避免阻塞 DOM。 提前謝謝了。

全局事件處理程序

會有人支持和反對任何事情,包括空氣分子的運動,但歸根結底,重要的是你能夠做你需要做的事情,並且在這個過程中保持井井有條。 在 JAB Creations web 平台上,我們在適當的情況下使用全局事件,有時我們會在必要時設置特定元素的事件。

//Do not shorten event to e, you WILL want to reference e separately.
window.onclick = function(event)
{
 if (condition) {}
 else if (condition) {}
}

設置特定事件:

  1. 通常,您需要檢查section()page()是否合適(假設您有適當的信息層次結構)。
  2. 你會想要一個 function 返回當前頁面的 id,在我的情況下,這是push_current_id()id_(push_current_id()) (例如push_current_id() == 'admin_'用於控制面板並且在字符限制解除之前HTML5 中的id屬性)。
  3. 在某些情況下,為特定元素設置 static 事件是可以的,盡管您通常希望具有普遍適用的行為:

CTRL + 水平滾動:

window.onwheel = function(event)
{
 if (event.ctrlKey)
 {
  if (e.scrollHeight > e.clientHeight && event.deltaY != 0)
  {
   event.preventDefault();
   //Change 5 to adjust sensitivity.
   e.scrollLeft = e.scrollLeft + (5 * event.deltaY);
  }
  //else if (condition) {}//Other behavioral tweaks.
 }
 //else if (condition) {}//Other behavioral tweaks.
}

主要的收獲是,如果不是所有事件調用,您都限制了對全局處理程序的大部分事件調用,並且您可以在元素掛鈎到這些全局事件的某些部分所需的條件上盡可能具體或廣泛。 您不需要添加/刪除事件,只需調整您的if條件。 我敢肯定,有人會強烈反對,盡管我們在整個 web 平台上使用這種方法取得了成功,該平台旨在在沒有框架和庫的情況下明確工作以最大限度地提高性能。

這是我對迄今為止所學知識的看法。

cs.js

(function () {
    document.addEventListener("DOMContentLoaded", function (event) {
        let component = RGDM.MainComponent();
        component.init("rgDiv");
    });
})();

mainComponent.js

var RGDM = RGDM || {};
RGDM.MainComponent = function () {
    let divMain;
    let lineBreak;
    function init(id) {
        divMain = document.getElementById(id);
        loadUI();
    }

    function loadUI() {
        let component = RGDM.Component();
        component.init(divMain);

        lineBreak = document.createElement("br");
        divMain.appendChild(lineBreak);
        let btnResult = document.createElement("a");
        btnResult.innerHTML = "Result";
        btnResult.style.backgroundColor = "#fff";
        btnResult.style.border = "1px solid #999";
        btnResult.style.padding = "5px 5px 5px 5px";
        btnResult.style.color = "#000";
        btnResult.style.cursor = "pointer";
        btnResult.id = "btnResult";
        btnResult.onclick = function () {
            if (component.value() != "") {
                document.getElementById("labelMainDisplay").innerHTML = "OUTSIDE_COMPONENT:" + component.value();
            } else {
                document.getElementById("labelMainDisplay").innerHTML = "[Display Outside Component]";
            }
        }
        divMain.appendChild(btnResult);
        lineBreak = document.createElement("br");
        divMain.appendChild(lineBreak);
        lineBreak = document.createElement("br");
        divMain.appendChild(lineBreak);
        let labelMainDisplay = document.createElement("span");
        labelMainDisplay.id = "labelMainDisplay";
        labelMainDisplay.innerHTML = "[Display Outside Component]";
        divMain.appendChild(labelMainDisplay);

        divMain.appendChild(componentDiv);
    }


    return {
        init: init
    };
}

組件.js

var RGDM = RGDM || {};
RGDM.Component = function () {
    let divMain;
    let componentDiv;
    function init(div) {
        divMain = div
        loadUI();
    }
    function loadUI() {
        let componentDiv = document.createElement("div");
        componentDiv.style.height = "200px";
        componentDiv.style.width = "300px";
        componentDiv.style.padding = "10px 10px 10px 10px";
        componentDiv.style.border = "1px solid #000";
        componentDiv.addEventListener("click", function (e) {
            console.log(JSON.stringify(e.target.nodeName));
            if (e.target && e.target.nodeName == "A") {
                // console.log("List item ", e.target.id.replace("post-", ""), " was clicked!");
                if (e.target.id == "btnSubmit") {
                    if (document.getElementById("txtName").value !== "") {
                        document.getElementById("labelDisplay").innerHTML = "INSIDE_COMPONENT:" + document.getElementById("txtName").value;
                    } else {
                        document.getElementById("labelDisplay").innerHTML = "[Display Text]";
                    }
                } else if (e.target.id == "btnClear") {
                    document.getElementById("txtName").value = "";
                }
            }
        });

        let txtName = document.createElement("input");
        txtName.id = "txtName";
        txtName.type = "input";
        componentDiv.appendChild(txtName);

        let btnSubmit = document.createElement("a");
        btnSubmit.innerHTML = "Submit";
        btnSubmit.style.backgroundColor = "#000";
        btnSubmit.style.border = "1px solid #000";
        btnSubmit.style.padding = "5px 5px 5px 5px";
        btnSubmit.style.color = "#fff";
        btnSubmit.style.cursor = "pointer";
        btnSubmit.id = "btnSubmit";
        componentDiv.appendChild(btnSubmit);

        let btnClear = document.createElement("a");
        btnClear.innerHTML = "Clear";
        btnClear.id = "btnClear";
        btnClear.style.backgroundColor = "red";
        btnClear.style.border = "1px solid #ccc";
        btnClear.style.padding = "5px 5px 5px 5px";
        btnClear.style.color = "#fff";
        btnClear.style.cursor = "pointer";
        componentDiv.appendChild(btnClear);

        let breakLine = document.createElement("br");
        componentDiv.appendChild(breakLine);

        let labelDisplay = document.createElement("span");
        labelDisplay.id = "labelDisplay";
        labelDisplay.innerHTML = "[Display Text]";
        componentDiv.appendChild(labelDisplay);

        divMain.appendChild(componentDiv);
    }

    function getResult() {
        return document.getElementById("txtName").value;
    }
    function getComponent() {
        return componentDiv;
    }
    return {
        init: init
        , component: getComponent
        , value: getResult
    };
};

下面是截圖

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM