https://angularfirebase.com/lessons/methods-for-debugging-an-angular-application/
https://www.youtube.com/watch?time_continue=9&v=gxixM90vo9Y, around 5:32
this.db.object('items/12345/title')
.do(val => console.log('before map', val) )
.map(title => title.$value.toUpperCase() )
.do(val => console.log('after map', val) )
Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts
Saturday, November 4, 2017
Spring boot supports Cross domain request (CORS)
https://spring.io/guides/gs/rest-service-cors/
@CrossOrigin(origins = "http://localhost:9000")
This @CrossOrigin annotation enables cross-origin requests only for this specific method. By default, its allows all origins, all headers, the HTTP methods specified in the @RequestMappingannotation and a maxAge of 30 minutes is used. You can customize this behavior by specifying the value of one of the annotation attributes: origins, methods, allowedHeaders, exposedHeaders, allowCredentials or maxAge. In this example, we only allow http://localhost:9000 to send cross-origin requests.
https://vimsky.com/article/2252.html
@CrossOrigin(origins = "http://localhost:9000")
https://vimsky.com/article/2252.html
Friday, September 15, 2017
Proxy Api Calls in Vue2
The big advantage is we don't have to worry about CORS
https://github.com/prograhammer/vue-example-project#proxy-api-calls-in-webpack-dev-server
npm install --save vue-resource
npm install --save-dev http-proxy-middleware
in build/index.js add
If it is configured properly, you will see this when the node server is started.
in .js file
https://github.com/hairinwind/myVue/blob/master/src/components/HttpProxy.vue
https://github.com/prograhammer/vue-example-project#proxy-api-calls-in-webpack-dev-server
npm install --save vue-resource
npm install --save-dev http-proxy-middleware
in build/index.js add
'/service': { target: 'http://services.groupkt.com', changeOrigin: true, ws: true, // proxy websockets pathRewrite: { '^/service/state/': '/state/get/' // http://localhost:8080/service/state/ => http://services.groupkt.com/state/get/ }, router: { } }
If it is configured properly, you will see this when the node server is started.
[HPM] Proxy created: /service -> http://services.groupkt.com [HPM] Proxy rewrite rule created: "^/service/state/" ~> "/state/get/"
in .js file
// send request to http://localhost:8080/service/state/USA/all will be eventually sent to http://services.groupkt.com/state/get/USA/all this.$http.get('/service/state/USA/all', {}) .then(response => { this.states = response.body.RestResponse.result }, response => { console.log("error"); console.log(response) });
https://github.com/hairinwind/myVue/blob/master/src/components/HttpProxy.vue
webpack and Jquery-ui
Here is the way to integrate jquery-ui in webpack project
https://stackoverflow.com/questions/33998262/jquery-ui-and-webpack-how-to-manage-it-into-module
https://github.com/hairinwind/myVue/blob/master/build/webpack.base.conf.js
https://github.com/hairinwind/myVue/blob/master/src/components/JqueryUI.vue
npm install jquery-ui-dist --save
webpack.config.js
resolve: {
alias: {
'jquery-ui': 'jquery-ui-dist/jquery-ui.js'
}
},
...
plugins: [
new webpack.ProvidePlugin({
'jQuery': 'jquery',
'$': 'jquery',
'global.jQuery': 'jquery'
})
],
In the .js file, load the modulerequire('jquery-ui'); //or import 'jquery-ui'
Referencehttps://stackoverflow.com/questions/33998262/jquery-ui-and-webpack-how-to-manage-it-into-module
https://github.com/hairinwind/myVue/blob/master/build/webpack.base.conf.js
https://github.com/hairinwind/myVue/blob/master/src/components/JqueryUI.vue
Thursday, September 7, 2017
vue basic
The data are only reactive if they existed when the instance was created. That means if you add a new property, like: vm.b = 'hi' Then changes to b will not trigger any view updates.
https://vuejs.org/v2/guide/instance.html
Computed properties are cached based on their dependencies. A computed property will only re-evaluate when some of its dependencies have changed. In the example above, only when message is changed, the reversedMessage will be recalculated. The following computed property will never update, because Date.now() is not a reactive dependency
When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue
When you modify the length of the array, e.g. vm.items.length = newLength
To overcome caveat 1, both of the following will accomplish the same as vm.items[indexOfItem] = newValue, but will also trigger state updates in the reactivity system:
#############解决办法###############
在目录build下面找到webpack.prod.conf.js文件,找到output节点,添加【publicPath:'./'】
npm run build
从 dist 目录下 copy index.html 和 static 去 web server 就可以
https://zmis.me/detail_1001
Comparison with Other Frameworks
https://vuejs.org/v2/guide/comparison.html
example project
https://github.com/prograhammer/vue-example-project#configure-eslint
http://vuetips.com/
vuex
https://alligator.io/vuejs/intro-to-vuex/
https://vuejs.org/v2/guide/instance.html
computed:
var vm = new Vue({ el: '#example', data: { message: 'Hello' }, computed: { // a computed getter reversedMessage: function () { // `this` points to the vm instance return this.message.split('').reverse().join('') } } })
Computed properties are cached based on their dependencies. A computed property will only re-evaluate when some of its dependencies have changed. In the example above, only when message is changed, the reversedMessage will be recalculated. The following computed property will never update, because Date.now() is not a reactive dependency
computed: { now: function () { return Date.now() } }https://vuejs.org/v2/guide/computed.html
List rendering
Due to limitations in JavaScript, Vue cannot detect the following changes to an array:When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue
When you modify the length of the array, e.g. vm.items.length = newLength
To overcome caveat 1, both of the following will accomplish the same as vm.items[indexOfItem] = newValue, but will also trigger state updates in the reactivity system:
// Vue.set Vue.set(example1.items, indexOfItem, newValue) // Array.prototype.splice example1.items.splice(indexOfItem, 1, newValue)To deal with caveat 2, you can use splice:
example1.items.splice(newLength)
https://vuejs.org/v2/guide/list.htmlTo register my component globally
in main.jsimport Panel from './components/Panel' Vue.component('panel', Panel)
Programmatic Navigation
this.$router.push({ name: 'Hello' })https://router.vuejs.org/en/essentials/navigation.html
build and deploy PR env
打开chrome的审查元素,发现console出现了几个错误,原来打包的几个文件都是404 NOT FOUND.#############解决办法###############
在目录build下面找到webpack.prod.conf.js文件,找到output节点,添加【publicPath:'./'】
npm run build
从 dist 目录下 copy index.html 和 static 去 web server 就可以
https://zmis.me/detail_1001
Reference
https://scotch.io/tutorials/getting-started-with-vue-routerComparison with Other Frameworks
https://vuejs.org/v2/guide/comparison.html
example project
https://github.com/prograhammer/vue-example-project#configure-eslint
http://vuetips.com/
vuex
https://alligator.io/vuejs/intro-to-vuex/
Wednesday, June 7, 2017
ember.js practice
-install ember-cli
npm install -g ember-cli
- create project
ember new hello-world
--start server
ember server
- create controller
ember g controller application
- create route
ember g route about
ember g route parent
ember g route parent/child
--create component
ember g component x-counter
-- script on page
npm install -g ember-cli
- create project
ember new hello-world
--start server
ember server
- create controller
ember g controller application
- create route
ember g route about
ember g route parent
ember g route parent/child
--create component
ember g component x-counter
-- script on page
{{#unless showName}} <h2 id="title">Hello {{name}}</h2> {{else}} <h2 id="title">Hello Ember</h2> {{/unless}} <button {{action 'toggleName'}}>Toggle Name</button> <br/> {{numClicks}} Click <button {{action 'incrementClicks'}}>Increment</button>
Monday, May 1, 2017
Monday, March 27, 2017
Javascript asynchronous and promise
The javascript is now using lots of asynchronous call. In some scenarios, you need an asynchronous call chain, one after another. Promise can help on asynchronous chain.
Here is the requirement.
The UI display a task list. Each task has a priority, which determines the display order on the UI.
There is up arrow and down arrow on the right of each task. Clicking the up arrow will exchange the priority with the task above.
The code here is nodejs and mongoose.
Here is the pseudo code.
//find current task by taskId
//find the previous task based on the current task priority
//exchange the priority
//save the tasks (update first task, once it is done, in the callback update the second task)
There are at least 4 callback functions embedded. The code is hard for reading.
With Promise, the code could be refactored like this. It is much neat and easy for reading.
For code "Task.findById(id)", Mongoose returns a promise.
Once the record is returned, the method then is executed. It calls the function "findThisAndPreviousTaskByPriority", which returns two records in an array.
the function then returns a promise as well. Once the inside function returns, it triggers the next "then", which is exchangePriority. It also returns an array contains two tasks, but their priorities have already been exchanged. "updateTwoTasksPriority" basically creates two mongoose update promise based on the two tasks. The last function call uses "Promise.all" to convert a promises Iterate into one single promise.
Here are some good articles about javascript promise
https://davidwalsh.name/promises
http://stackoverflow.com/questions/39028882/chaining-async-method-calls-javascript
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://www.youtube.com/watch?v=s6SH72uAn3Q
https://60devs.com/best-practices-for-using-promises-in-js.html
http://mongoosejs.com/docs/promises.html
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
http://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises
There are at least 4 callback functions embedded. The code is hard for reading.
With Promise, the code could be refactored like this. It is much neat and easy for reading.
For code "Task.findById(id)", Mongoose returns a promise.
Once the record is returned, the method then is executed. It calls the function "findThisAndPreviousTaskByPriority", which returns two records in an array.
the function then returns a promise as well. Once the inside function returns, it triggers the next "then", which is exchangePriority. It also returns an array contains two tasks, but their priorities have already been exchanged. "updateTwoTasksPriority" basically creates two mongoose update promise based on the two tasks. The last function call uses "Promise.all" to convert a promises Iterate into one single promise.
Here are some good articles about javascript promise
https://davidwalsh.name/promises
http://stackoverflow.com/questions/39028882/chaining-async-method-calls-javascript
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://www.youtube.com/watch?v=s6SH72uAn3Q
https://60devs.com/best-practices-for-using-promises-in-js.html
http://mongoosejs.com/docs/promises.html
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
http://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises
Friday, March 17, 2017
Angular 2 use local jquery and bootstrap
I use angular 2 cli to create the angular 2 project.
To use the jquery js or bootstrap css on local, add the configuration below into angular-cli.json
To use the jquery js or bootstrap css on local, add the configuration below into angular-cli.json
Wednesday, March 8, 2017
Monday, March 6, 2017
Thursday, March 2, 2017
process.env.POST
In Nodejs, you can see the code like this
the port is either process.env.PORT or 3000.
The "process.evn.PORT" can be passed in by command line argument. For example:
now the port is 4444.
Sometimes the setting may be env specific, e.g. database URL. Here is one solution.
https://gist.github.com/wilsonbalderrama/0ad2b64b5ab6287c7318
config.js
the port is either process.env.PORT or 3000.
The "process.evn.PORT" can be passed in by command line argument. For example:
now the port is 4444.
Sometimes the setting may be env specific, e.g. database URL. Here is one solution.
https://gist.github.com/wilsonbalderrama/0ad2b64b5ab6287c7318
config.js
Thursday, October 6, 2016
Tuesday, September 20, 2016
javascript closure
A closure is a data structure that binds a function to its environment at the moment it’s declared.
Closures are readily seen in the case of nested functions.
Closures are readily seen in the case of nested functions.
Javascript tail-call
Having a function call as the last thing to run in a recursive function allows the JavaScript runtime to realize it doesn’t need to hold on to the current stack frame any longer, because it doesn’t have any more work to do; so it discards the stack frame. (only ES6 has this optimization)
this is the tail-call
this is the tail-call
Wednesday, April 27, 2016
browserify, jasmine, karma, istanbul
Browserify lets you require('modules') in the javascript by bundling up all of your dependencies.
Jasmine is used to do the javascript unit test.
Karma is the javascript unit test runner.
Istanbul is used for javascript coverage.
I have my javascript using browserify. Then I created jasmine to test my javascript. Then I configured Karma to run my jasmine. The last step I want to get Istanbul coverage report to see how many code is not covered by unit test.
It is all good until I try to integrate Istanbul. Karma supports Istanbul out of box by Karma coverage. But the problem is that it does not with js in Browserify style.
After did a lot of try and reading a lot of posts from internet, I found a workaround. Here is the my karma.conf.js The tricky is that in "preprocessors" only put in "browserify", without "coverage". The karma tutorial let you put in "coverage" here if you want to have Istanbul coverage report. But I found it did not work with browserify. In "Browserify", we weave in Istanbul. Here is the dependencies needed. My project is a java maven project. I also want the javascript unit test is executed every time the build happens. In my pom.xml, I need add plugin The last execution is running karma.
Jasmine is used to do the javascript unit test.
Karma is the javascript unit test runner.
Istanbul is used for javascript coverage.
I have my javascript using browserify. Then I created jasmine to test my javascript. Then I configured Karma to run my jasmine. The last step I want to get Istanbul coverage report to see how many code is not covered by unit test.
It is all good until I try to integrate Istanbul. Karma supports Istanbul out of box by Karma coverage. But the problem is that it does not with js in Browserify style.
After did a lot of try and reading a lot of posts from internet, I found a workaround. Here is the my karma.conf.js The tricky is that in "preprocessors" only put in "browserify", without "coverage". The karma tutorial let you put in "coverage" here if you want to have Istanbul coverage report. But I found it did not work with browserify. In "Browserify", we weave in Istanbul. Here is the dependencies needed. My project is a java maven project. I also want the javascript unit test is executed every time the build happens. In my pom.xml, I need add plugin The last execution is running karma.
Wednesday, February 10, 2016
javascript: setTimeout 0
means the function will be executed 5 seconds later.
but what does it mean if the time is set to 0, like this
it means the function will be deferred and executed at the end of the call stack (the currently executing method).
In this video, it explains it.
https://www.youtube.com/watch?v=8aGhZQkoFbQ
http://danmartensen.svbtle.com/events-concurrency-and-javascript
Call Stack, web api, event loop, callback queue
In a method, setTimeout(func, 0) was executed.
http://latentflip.com/loupe/
Click "Save+Run"
Also, the javascript engine tries to do the render job every 16 milliseconds if the call stack is empty.
The render job is higher priority than the callback queue.
But if you have a lot of callback in the queue, and each callback can take a long time. It slows down the rendering.
but what does it mean if the time is set to 0, like this
it means the function will be deferred and executed at the end of the call stack (the currently executing method).
In this video, it explains it.
https://www.youtube.com/watch?v=8aGhZQkoFbQ
http://danmartensen.svbtle.com/events-concurrency-and-javascript
Call Stack, web api, event loop, callback queue
In a method, setTimeout(func, 0) was executed.
- It will be first pushed "setTimeout(func, 0)" into the stack.
- Then the web APIs timer is running. (this does not block the stack)
- Once the time is over, pushed the callback function into callback queue.
- Once the stack is empty, the event loop will pick on callback from the callback queue ad push it into the stack.
- Then the callback function is executed.
http://latentflip.com/loupe/
Click "Save+Run"
Also, the javascript engine tries to do the render job every 16 milliseconds if the call stack is empty.
The render job is higher priority than the callback queue.
But if you have a lot of callback in the queue, and each callback can take a long time. It slows down the rendering.
how to test non-exports javascript function
Use rewire to test nonExported javascript function.
After rewire the target js file, you can use "__get__" to get the method you are going to test.
http://stackoverflow.com/questions/14874208/how-to-access-and-test-an-internal-non-exports-function-in-a-node-js-module
https://github.com/jhnns/rewire
After rewire the target js file, you can use "__get__" to get the method you are going to test.
http://stackoverflow.com/questions/14874208/how-to-access-and-test-an-internal-non-exports-function-in-a-node-js-module
https://github.com/jhnns/rewire
Thursday, July 2, 2015
javascript detect div height change, DOMSubtreeModified may help
In one of my project, it is implemented by "one page". Any request is an ajax call and the javascript refreshes the div when it gets data returned from ajax.
The div is using NiceScroll for scroll bar. The "resize" method of NiceScroll shall be triggered when the height of div is changed.
Now the javascript need detect the div height changing. I am using "DOMSubtreeModified".
The div is using NiceScroll for scroll bar. The "resize" method of NiceScroll shall be triggered when the height of div is changed.
Now the javascript need detect the div height changing. I am using "DOMSubtreeModified".
Monday, June 29, 2015
javascript Clone Arrays
To do a shallow copy, array.slice works
http://davidwalsh.name/javascript-clone-array
http://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
JQuery extend can also merge objects properties
http://api.jquery.com/jquery.extend/
another alternative is ramda clone
http://ramdajs.com/docs/#clone
http://davidwalsh.name/javascript-clone-array
http://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
slice
does not alter. It returns a shallow copy of elements from the original array. Elements of the original array are copied into the returned array as follows:- For object references (and not the actual object),
slice
copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays. - For strings and numbers (not
String
andNumber
objects),slice
copies strings and numbers into the new array. Changes to the string or number in one array does not affect the other array.
JQuery extend can also merge objects properties
http://api.jquery.com/jquery.extend/
another alternative is ramda clone
http://ramdajs.com/docs/#clone
Subscribe to:
Posts (Atom)