Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a single page application I'm working on in which a variable x can change for many reasons. I want the value displayed in the DOM (the div below) to at all times match the value of the javascript variable.
I understand frameworks like angular are good for this, but I'm looking for a more lightweight and simple solution. I'm already using JQuery and underscore.js on the page if that helps.
<script>
var x = 100
</script>
<div id="value_display">100</div>
Ideally I'd like something where I just need to provide the variable and the element as arguments. For example:
bind(x,'#value_display')
My proposition is to create special Class to encapsulate those variables. It is very lightweight solution no intervals and value watching.
var ViewModel=function(selector){
this.dom=document.querySelector(selector);//here DOM element
this.value=null;
};
//method sets value
ViewModel.prototype.set=function(value){
if (value===this.value)
return;//the same value
this.value=value;//new value
this.dom.innerText=this.value; //most important changing in DOM
};
//method gets value
ViewModel.prototype.get=function(){
return this.value;
};
Usage:
var x=new ViewModel("#selector");
x.set(100);
Check example in jsFiddle -https://jsfiddle.net/maciejsikora/wrd14kwk/
You ask for a simple implementation (no large frameworks) of an observer pattern, ideally just by providing the variable name and the element's id as arguments.
What you ask for is possible, if we define the bind() function to repeatedly poll x to see if it has changed. Note that bind then has to be called like this:
bind('x','value_display');
A working example:
var x = 100;
function bind(varName, elementId){
var lastValue;
function check(){
if(lastValue !== window[varName]){
lastValue = window[varName];
document.getElementById(elementId).innerHTML = lastValue;
}
}
//poll for changes every 50 milliseconds
setInterval(check, 50);
}
//bind x to value_display
bind('x','value_display');
//test function by changing x every 100th millisecond
setInterval(function(){
x = +new Date;
},
100
);
<div id="value_display"></div>
Personally, I would prefer a lightweight publisher/subscriber module over using a polling function, but that would require assignment to the variable x to be controlled by a function/method (some kind of setter). If you research (google) observer pattern or pub/sub pattern, you will find easy ways of implementing this in much less code than a large framework—but probably not as lightweight as the polling approach.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Just wondering, is there a specific reason to use a while loop as the game loop. Or could I use another method, like this one.
Note: this is not proper code, and has not been tested. This is just a general idea. This example is also not consistent to a specific coding language, but may follow mostly JavaScript because that's the coding language I know off the top of my head. I've actually tried something similar to this in dart (google flutter).
var startTime;
var running = false;
function loop1(){
startTime = system.currentMillis();
loop2();
}
loop2(){
gameUpdate();
//ignore my math, I did not focus on doing that property
//this is just an example and is not proper math
var delay = 1000 / (system.currentMillis() - startTime);
setTimeout(loop3, delay);
}
loop3(){
if(running){
loop1();
}
}
edit: could using something like this to avoid the need to use sleep(); be helpful to performance? (or phone battery)
It is perfectly possible to use your code as a main game loop. The reason why a while is preferred is because a main game loop executes endlessly until aborted, this is done simply with while (true) and aborting somewhere inside with break, or with while (abort == false) and setting abort = true somewhere inside. Notice that other loop variants such as for and do-while are more verbose, unless your language let's you do for (;;). Also note that you can restructure your proposed loop to a more simpler version using a while loop.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to understand the concept behind how monkey-patch works in JavaScript?
I've gone through too many examples but couldn't able to understand
For example - Monkey patching the dispatch function in Redux
let next = store.dispatch
store.dispatch = function dispatchAndLog(action) {
console.log('dispatching', action)
let result = next(action)
console.log('next state', store.getState())
return result
}
Source: http://redux.js.org/docs/advanced/Middleware.html#attempt-3-monkeypatching-dispatch
Can anyone please explain monkey patching in simple terms and example
And which is the best scenarios to use it?
Thanks.
Let say you use a library which define a class Test with a method test.
If you want to monkey patching-it you have to use this kind of code and include it after the library :
// replacing current implementation with a new one
Test.prototype.test = function(arg1, arg2, ...){...}
Now let say you want to do something a bit smarter, like adding something to the function without modifying the rest here is how you would do it :
var oldFN = Test.prototype.test;
Test.prototype.test = function([arguments...]){
[...some custom code...]
oldFN.apply(this, arguments);// arguments keyword refer to the list of argument that your function recevied, if you need something else use call.
[...some custom code...]
}
Monkey patching is valid but must be used wisely. Furthermore each time you upgrade the library, you must check that all your patches works still fine.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
What's a better practice, this:
myArray.forEach(function(item)) {
doSomething(item);
function doSomething(an_item) {
console.log(an_item);
}
}
or this:
myArray.forEach(function(item)) {
doSomething(item);
}
function doSomething(an_item) {
console.log(an_item);
}
Does the first example create multiple instances of the function, or does it create it just the first time through the loop?
Thanks for any insight!
myArray.forEach(function(item)) {
doSomething(item);
}
function doSomething(an_item) {
console.log(an_item);
}
this function is best because it will created only one time ;
and
myArray.forEach(function(item)) {
doSomething(item);
function doSomething(an_item) {
console.log(an_item);
}
}
is a bad due to every time function will create during loop process
The second. Use the second form (because the first form will slow down your user's experience, which may well be a phone or low powered device), or the even shorter form
myArray.forEach(doSomething);
function doSomething(element, index, array) {
console.log("myArray[" + index + "] = " + element);
}
It really depends on the interpreter if your asking a pure question about performance, i would imagine some of the smarter ones would be good enough to not create and destroy the function each time if they never change during the loop but realistically thats what your telling it to do (Create the function each time as the scope is temporary) so don't be surprised if thats the case. imagine if for example you were dynamically creating a closure within the forEach, wouldn't each loop need to create a new copy of the function?
http://jsperf.com/closure-vs-name-function-in-a-loop/2
certianly I would imagine older browsers not being smart enough to know to only make it once.
another post: Don't make functions within a loop
I agree with what the others have said, and +1 on the second solution. You don't ever want to define/create functions within loops.
**Bonus
If you're function has to do with an object within the forloop, you can use this in your helper instead of passing the object via a parameter:
Example:
var myArray = [{ a: 1 }, { a: 2 }, { a: 3 }];
myArray.forEach(function(item) {
doSomething.call(item);
});
function doSomething(item) {
console.log(this.a);
}
It is good practice to always define things in the smallest scope possible.
So when you don't need the function elsewhere, defining it in the loop which uses it is the best choice.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have lot enough functions, which look like:
var functionName = function(e) {
//
};
where all the parameters are getting passed in in a single container e. Most times values are simple values (no functions), ex.:
{ parameter1: 1, parameter2: "Name", parameter3:{ subParameter1: "A"}}
But there're times when I pass in functions as in: { p2:function(){...} }
I have two options when it comes to utilising parameter values:
Options 1: get parameter values from the chain, starting from e: e.parameter1, e.parameter3.subParameter1 etc.
Option 2: use cached parameter values:
var parameter1 = e.parameter1;
var subParameter1 = e.parameter3.subParameter1;
The second option improves readability but increases the number of vars and the size of the code base. On another hand it's much drier when using long chains, i.e. e.p1.p2.p3 etc.
What reasoning should I use for choosing between those two options?
**Update 1 - the question sounds quite subjective, let me re-prase it.**
I don't mind using chains all the way, no local vars codebase is smaller, I can always figure out what's what, are the any cases when caching is a must?
A combination, based on depth(e.p1 vs e.p1.sp2.ssp3) and frequency of use. Deeper sub-properties and high usage of any sub-property both benefit from caching.
Nested property look ups can get costly, and caching the value after executing the look up once is valuable if you're going to use it a lot. This is only more efficient if you're accessing a particular property on the chain more than once, and the more you access it, the more you benefit from caching.
If you only have one level deep(e.p1, e.p2, e.p3) and you're only looking up each property value once, don't bother.
If you're accessing e.p1.sp2.ssp3 all throughout your function, cache it for sure.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Note: This is a continuation of another question that I decided were two separate issues that need to be solved. I'm also currently not sure of how exactly to phrase this question, so I will try my best and when I get more clarity I will rephrase my question for future reference.
I'm writing two basic jQuery plugins, $.fn.query and $.fn.build, that sort an array, and create html code to insert into a document, respectively. I'm currently testing it with Vimeo video ID's that I will display videos with.
$.fn.build has three parts. First it wraps every array item with individual containers, the builds them into rows (problem area), then lastly it wraps everything in a container. (every part of this is optional).
Specifically the problem comes from this line: $(tmp).add(newRow); although it is valid javascript.
if ( options.splitBy !== undefined && options.wrapRow !== undefined ) {
var tmp = $([]),
newRow = function(i) {
$(build.splice( i, i + options.splitBy )).wrapAll( options.wrapRow ).parent();
};
for (var i = 0, l = build.length, a = options.splitBy; i < l; i += a) {
$(tmp).add(newRow);
}
build = tmp;
console.log(build);
}
See: http://jsbin.com/upatus/2/edit
I am quite sure that you want to use the function, instead of adding the function itself. Also, you will want to use the same tmp object all over the time, instead of wrapping it into a new jQuery instance and not adding to the original one. Try
tmp.add(newRow(i));
BTW: If you want to build an array, you should use
var tmp = [];
and
tmp.push(…);
Now I've looked at the code from the other question. Both answers are correct, and contain some valid points:
splice is an Array function on jQuery's prototype, and returns an array. (You have fiexd this now)
Your query method returns an array, but should return a jQuery instance for chaining
Your build variable was not initialized, but used
You should really choose whether you want to use arrays or jQuery objects internally in your function, and not mix them.
BTW, you should rename your functions to more descriptive names. "build" and "query" are very vague and may collide with other plugins.