Just wondering, is this a valid way to define an explicit function inside JavaScript's addEventListener
function so that it could be removed at any time using removeEventListener
?
var somefunction;
window.addEventListener('load', somefunction = function(){
//do something
}, false);
window.removeEventListener('load', somefunction, false);
In other words, is it ok to define a variable somefunction
and then assign an anonymous function to it inside addEventListener
, instead of defining somefunction
outright from the get go? It seems to work in FF and Chrome, but just wanna make sure this is officially valid JavaScript syntax.
答案 0 :(得分:3)
Yes, it will work. An assignment is an expression -- it assigns to the variable and also returns the value that it assigned.
Personally I think this is a confusing way to write it. If you're refer to the function by name, put the definition where you define the name, not where you use it. In particular, if you try to do this twice, you'll have a problem because each event listener will have a different function, but it has the same name.
window.addEventListener('event1', somefunction = function() {
//do something
});
window.addEventListener('event2', somefunction = function() {
//do something
});
Now you can only remove event2
, because somefunction
no longer refers to the function that was added to event1
.
答案 1 :(得分:1)
只要removeEventListener
说“点击”即可。 event作为参数,任何一个 eventListener注册到'点击'活动将被删除。这在OP的案例中很明显,因此根据前面提到的标准是可行的。
以下代码段演示了已注册的eventListener已添加到#target1
以收听'点击'事件。它将一直有效,直到调用removeEventListener()
在4秒内删除eventListener。请注意,此特定removeEventListener
的参数为:
click
eventLog()
false
识别参数是'点击' target.event
为#target
,removeEventListener()
允许var eventLog;
var tgt1 = document.getElementById('target1');
var term = document.getElementById('btn');
tgt1.addEventListener('click', eventLog = function(e) {
console.log('target1 has been clicked');
}, false);
setTimeout(function() {
tgt1.removeEventListener('click', eventLog, false);
eventLog('Target1 eventListener is removed');
}, 4000);
function eventLog(str) {
console.log(str);
}
识别其目标。
#target1 {
border: 2px solid red;
}

<p>Start clicking TARGET1 several times and you'll notice that each `click` event is firing as displayed in the console. Within 4 seconds, TARGET1's eventListener should be removed.</p>
<div id='target1'>TARGET1</div>
&#13;
string s = "http://sp2013/sites/1234";
var firstURLlastPart = new Uri(s).Segments.Last();
string s = "http://sp2013/pwa/projectsites/projectdetails.aspx?projuid=1234-123-123-123456-123456";
var secondURLlastPart = s.Split('=').Last();
&#13;