Search Results

Search found 7724 results on 309 pages for 'backbone js'.

Page 5/309 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Dealing with the node.js callback pyramid

    - by thecoop
    I've just started using node, and one thing I've quickly noticed is how quickly callbacks can build up to a silly level of indentation: doStuff(arg1, arg2, function(err, result) { doMoreStuff(arg3, arg4, function(err, result) { doEvenMoreStuff(arg5, arg6, function(err, result) { omgHowDidIGetHere(); }); }); }); The official style guide says to put each callback in a separate function, but that seems overly restrictive on the use of closures, and making a single object declared in the top level available several layers down, as the object has to be passed through all the intermediate callbacks. Is it ok to use function scope to help here? Put all the callback functions that need access to a global-ish object inside a function that declares that object, so it goes into a closure? function topLevelFunction(globalishObject, callback) { function doMoreStuffImpl(err, result) { doMoreStuff(arg5, arg6, function(err, result) { callback(null, globalishObject); }); } doStuff(arg1, arg2, doMoreStuffImpl); } and so on for several more layers... Or are there frameworks etc to help reduce the levels of indentation without declaring a named function for every single callback? How do you deal with the callback pyramid?

    Read the article

  • Getting Started With Knockout.js

    - by Pawan_Mishra
    Client side template binding in web applications is getting popular with every passing day. More and more libraries are coming up with enhanced support for client side binding. jQuery templates is one very popular mechanism for client side template bindings. The idea with client side template binding is simple. Define the html mark-up with appropriate place holder for data. User template engines like jQuery template to bind the data(JSON formatted data) with the previously defined mark-up.In this...(read more)

    Read the article

  • attaching js files to one js file but with JQuery error !

    - by uzay95
    Hi, I wanted to create one js file which includes every js files to attach them to the head tag where it is. But i am getting this error Microsoft JScript runtime error: Object expected this is my code: var baseUrl = document.location.protocol + "//" + document.location.host + '/yabant/'; // To find root path with virtual directory function ResolveUrl(url) { if (url.indexOf("~/") == 0) { url = baseUrl + url.substring(2); } return url; } // JS dosyalarinin tek noktadan yönetilmesi function addJavascript(jsname, pos) { var th = document.getElementsByTagName(pos)[0]; var s = document.createElement('script'); s.setAttribute('type', 'text/javascript'); s.setAttribute('src', jsname); th.appendChild(s); } addJavascript(ResolveUrl('~/js/1_jquery-1.4.2.min.js'), 'head'); $(document).ready(function() { addJavascript(ResolveUrl('~/js/5_json_parse.js'), 'head'); addJavascript(ResolveUrl('~/js/3_jquery.colorbox-min.js'), 'head'); addJavascript(ResolveUrl('~/js/4_AjaxErrorHandling.js'), 'head'); addJavascript(ResolveUrl('~/js/6_jsSiniflar.js'), 'head'); addJavascript(ResolveUrl('~/js/yabanYeni.js'), 'head'); addJavascript(ResolveUrl('~/js/7_ResimBul.js'), 'head'); addJavascript(ResolveUrl('~/js/8_HaberEkle.js'), 'head'); addJavascript(ResolveUrl('~/js/9_etiketIslemleri.js'), 'head'); addJavascript(ResolveUrl('~/js/bugun.js'), 'head'); addJavascript(ResolveUrl('~/js/yaban.js'), 'head'); addJavascript(ResolveUrl('~/embed/bitgravity/functions.js'), 'head'); }); Paths are right. I wanted to show you folder structure and watch panel: Any help would be greatly appreciated.

    Read the article

  • Backbone.js not registering Model.hasChanged event

    - by Brian M. Hunt
    Hello, I'm trying to get a View in Backbone.js to save when there's a 'change' event if (and only if) the data has changed. Long story short, I've a 'change' event set on the View that calls this: function changed_event() { log.debug("Before: " + this.model.get('name')) // not 'contrived!' this.model.set({'name': 'contrived!'}); log.debug("After: " + this.model.get('name')) // 'contrived!' if (this.model.hasChanged()) { alert("This is never called."); } } I'd like to know why the model.hasChanged() is false when clearly the model has been changed. I'm not sure what other information is necessary, but if there is more information that may be helpful please comment and I'll elaborate. Thank you for reading.

    Read the article

  • only update certain model attributes using Backbone.js

    - by Drew Dara-Abrams
    With Backbone, I'm trying to update and save to the server just one attribute: currentUser.save({hide_explorer_tutorial: 'true'}); but I don't want to send all the other attributes. Some of them are actually the output of methods on the server-side and so they are not actually true attributes with setter functions. Currently I'm using unset(attribute_name) to remove all the attributes that I don't want to update on the server. Problem is those attributes are then no longer available for local use. Suggestions on how to only save certain attributes to the server?

    Read the article

  • Backbone: rendering syntax

    - by ksol
    We're using Backbone.js in one of my team's projects, and this is the first time I use it. I've seen many times this kind of code (it's coffeescript, but clear enough I think. @ means this.) clients_view = new Homespa.Views.Orders.Clients.SectionView(collection: @options.clients) @$("#clients-section").html(clients_view.render().el) clients_search_view = new Homespa.Views.Orders.Clients.SearchView @$("#clients_search_modal").html(clients_search_view.render().el) Isn't there a better way to do this? I would expect to just call render on my view, and then everything's good, I shouldn't have to get the html and append/replace it by hand. Thanks for you time !

    Read the article

  • Sync issue in collection fetch backbone

    - by Stefano Maglione
    i'm fetching a collection but i've problem because into the collection the function parse use an another ajax call.So if i try to console.log the response of fetch after the fetch linecode but it is ever undefined. Function call fetch: friends: function(){ var amici=new Amicizie(); var amicilist=amici.fetch(); console.log(amicilist);<---undefined,because executed before fetch collection called: var obj={}; var Amicizie = Backbone.Collection.extend({ url:'https://api.parse.com/1/classes/User/', parse: function(data) { var cur_user=Parse.User.current().id; $.ajax({ type: 'GET', headers: {'X-Parse-Application-Id':'qS0KL***EM1tyhM9EEPiTS3VMk','X-Parse-REST-API- Key':'nh3eoUo9G***JIfIt1Gm'}, url: "https://api.parse.com/1/classes/_User/?where=....", success: function(object) { console.log(object ); obj=object; console.log(obj ); }, error: function(data) { console.log("ko" ); } }); return obj.results; } }); return Amicizie; });

    Read the article

  • loading js files dynamically via another js file?

    - by mark smith
    Hi there, is there anyway to load other JS files from within a single JS file. I would like to point my individual pages "ITS" js file and that js file would load jquery, other js files. I know i can just pop all these into the html i.e. I was thinking of separations of concerns so i was wondering if anything exists already without me reinventing the wheel.... That i would just need to edit home.js to change what other js (jquery etc) are loaded for home.htm ... home.htm would just point to home.js Thanks

    Read the article

  • rest and client rights integration, and backbone.js

    - by Francois
    I started to be more and more interested in the REST architecture style and client side development and I was thinking of using backbone.js on the client and a REST API (using ASP.NET Web API) for a little meeting management application. One of my requirements is that users with admin rights can edit meetings and other user can only see them. I was then wondering how to integrate the current user rights in the response for a given resource? My problem is beyond knowing if a user is authenticated or not, I want to know if I need to render the little 'edit' button next to the meeting (let's say I'm listing the current meetings in a grid) or not. Let's say I'm GETing /api/meetings and this is returning a list of meetings with their respective individual URI. How can I add if the user is able to edit this resource or not? This is an interesting passage from one of Roy's blog posts: A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) and set of standardized media types that are appropriate for the intended audience (i.e., expected to be understood by any client that might use the API). From that point on, all application state transitions must be driven by client selection of server-provided choices that are present in the received representations or implied by the user’s manipulation of those representations It states that all transitions must be driven by the choices that are present in the representation. Does that mean that I can add an 'editURI' and a 'deleteURI' to each of the meeting i'm returning? if this information is there I can render the 'edit' button and if it's not there I just don't? What's the best practices on how to integrate the user's rights in the entity's representation? Or is this a super bad idea and another round trip is needed to fetch that information?

    Read the article

  • Backbone.js routes not firing

    - by drale2k
    I have a Base Router where i define some functions that need to be run everywhere. Every Router extends this Router. Now my problem is, that none of my routes defined in this Base router, actually fire. Every other route in other Routers work fine. I have created a test route called 'a' which calls method 'b', which should fire an alert but nothing happens. Here is the code: (This is Coffeescript, don't pay attention to the indentation, it's fine in my file) class Etaxi.Routers.Base extends Backbone.Router routes: 'register' : 'registerDevice' 'a' : 'b' b: -> alert "a" initialize: -> @registerDevice() unless localStorage.device_id? @getGeolocation() registerDevice: -> @collection = new Etaxi.Collections.Devices() @collection.fetch() view = new Etaxi.Views.RegisterDevice(collection: @collection) $('#wrapper').append(view.render().el) getGeolocation: -> navigator.geolocation.getCurrentPosition (position) -> lat = position.coords.latitude lng = position.coords.longitude #$('#apphead').tap -> # alert 'Position: ' + lat + " ," + lng So when i visit '/register' or '/a' it should fire the appropriate method but it does not. I wonder if it has something to do with the fact that other Router extend from this Router? Would be wired but it is the only thing i can think of because every other Router works fine.

    Read the article

  • Problems with Backbone.Model callback and THIS

    - by Rev. Samuel
    I'm building a simple weather widget. The current weather conditions are read out of the National Weather Service xml file and then I want to parse and store the relevant data in the model but the callback for the $.ajax won't connect (the way I'm doing it). var Weather = Backbone.Model.extend({ initialize: function(){ _.bindAll( this, 'update', 'startLoop', 'stopLoop' ); this.startLoop(); }, startLoop: function(){ this.update(); this.interval = window.setInterval( _.bind( this.update, this ), 1000 * 60 * 60 ); }, stopLoop: function(){ this.interval = window.clearInterval( this.interval ); }, store: function( data ){ this.set({ icon : $( data ).find( 'icon_url_name' ).text() }); }, update: function(){ $.ajax({ type: 'GET', url: 'xml/KROC.xml', datatype: 'xml' }) .done( function( data ) { var that = this; that.store( $( data ).find( 'current_observation' )[ 0 ] ); }); } }); var weather = new Weather(); The data is read correctly but I can't get the done function of the call back to call the store function. (I would be happy if the "done" would just parse and then do "this.set". Thanks in advance for your help.

    Read the article

  • Node.js, Nginx and Varnish with WebSockets

    - by Joe S
    I'm in the process of architecting the backend of a new Node.js web app that i'd like to be pretty scalable, but not overkill. In all of my previous Node.js deployments, I have used Nginx to serve static assets such as JS/CSS and reverse proxy to Node (As i've heard Nginx does a much better job of this / express is not really production ready). However, Nginx does not support WebSockets. I am making extensive use of Socket.IO for the first time and discovered many articles detailing this limitation. Most of them suggest using Varnish to direct the WebSockets traffic directly to node, bypassing Nginx. This is my current setup: Varnish : Port 80 - Routing HTTP requests to Nginx and WebSockets directly to node Nginx : Port 8080 - Serving Static Assets like CSS/JS Node.js Express: Port 3000 - Serving the App, over HTTP + WebSockets However, there is now the added complexity that Varnish doesn't support HTTPS, which requires Stunnel or some other solution, it's also not load balanced yet (Perhaps i will use HAProxy or something). The complexity is stacking up! I would like to keep things simpler than this if possible. Is it still necessary to reverse proxy Node.js using Nginx when Varnish is also present? As even if express is slow at serving static files, they should theoretically be cached by Varnish. Or are there better ways to implement this?

    Read the article

  • nginx: js file loads indifferently every refresh

    - by poymode
    I have this nginx problem wherein a js file in a rails app loads indifferently. Whenever I try to access the JS file in the browser and refresh the page, the scrollbar changes length meaning sometimes it loads half the js page, sometimes the whole and sometimes just a part of it. the js file size is 71K. my nginx server is on different server,separate from my rails app. when I try to access the js file directly through the app server, lets say 10.48.30.150:3000/javascripts/file.js it works fine and doesnt show any half-loaded page. but when I use the nginx server which upstreams the rails app, it shows the indifferent page loads. here is my nginx http conf error_log /usr/local/nginx/logs/error.log; pid /usr/local/nginx/logs/nginx.pid; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; server_names_hash_bucket_size 256; access_log /usr/local/nginx/logs/access.log; sendfile on; #tcp_nopush on; keepalive_timeout 0; tcp_nodelay on; #gzip on; #gzip_min_length 4096; #gzip_buffers 16 8k; #gzip_types application/x-javascript text/css text/plain; large_client_header_buffers 4 8k; client_max_body_size 2G; include /usr/local/nginx/conf.d/*.conf; }

    Read the article

  • Simple Form validation failing Backbone

    - by Corey Buchillon
    Im not exactly adept at coding so Im probably missing something, but my view here is failing to refuse submission when one or both of the fields are empty. I have a feeling something isnt connected right to my template for the row and the view of the form Form = Backbone.View.extend({ //form vie el: '.item-form', initialize: function(){ }, events: { 'click #additem': 'addModel' }, addModel: function(itemName, price){ // simple validation before adding to collection if (itemName !="" && price !="" ){ var item = new Item({ itemName: this.$("#item").val(), price: this.$("#price").val()}); items.add(item); $("#message").html("Please wait; the task is being added."); item.save(null, {success: function (item, response,options) { item.id= item.attributes._id.$id; item.attributes.id = item.attributes._id.$id; new ItemsView({collection: items}); $("#message").html(""); } }); this.$("#item").val(''); this.$("#price").val(''); } else { alert('Please fill in both fields'); } } }); and HTML <table class="itemTable"> <thead> <tr> <th>Item</th> <th>Price</th> <th></th> </tr> </thead> <tbody class="tableBody"> <script type="text/template" id="table-row"> <td><%= itemName %></td> <td><%= price %></td> <td><button class="complete">Complete</button> <button class="remove">Remove</button></td> </script> </tbody> </table> <form class="item-form"> <input type="text" name="item" id="item" placeholder="Item"/> <!-- goes to itemName in the template for the body --> <input type="text" name="price" id="price" placeholder="Price" /><!--goes to price in the template for the body --> <button type="button" id="additem">Add</button> </form> <div id="message"></div>

    Read the article

  • backbone.js - Having multiple instances of the same view

    - by TrueWheel
    I am having problems having multiple instances in of the same view in different div elements. When I try to initialize them only the second of the two elements appear no matter what order I put them in. Here is the code for my view. var BodyShapeView = Backbone.View.extend({ thingiview: null, scene: null, renderer: null, model: null, mouseX: 0, mouseY: 0, events:{ 'click button#front' : 'front', 'click button#diag' : 'diag', 'click button#in' : 'zoomIn', 'click button#out' : 'zoomOut', 'click button#on' : 'rotateOn', 'click button#off' : 'rotateOff', 'click button#wireframeOn' : 'wireOn', 'click button#wireframeOff' : 'wireOff', 'click button#distance' : 'dijkstra' }, initialize: function(name){ _.bindAll(this, 'render', 'animate'); scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera( 15, 400 / 700, 1, 4000 ); camera.position.z = 3; scene.add( camera ); camera.position.y = -5; var ambient = new THREE.AmbientLight( 0x202020 ); scene.add( ambient ); var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.75 ); directionalLight.position.set( 0, 0, 1 ); scene.add( directionalLight ); var pointLight = new THREE.PointLight( 0xffffff, 5, 29 ); pointLight.position.set( 0, -25, 10 ); scene.add( pointLight ); var loader = new THREE.OBJLoader(); loader.load( "img/originalMeanModel.obj", function ( object ) { object.children[0].geometry.computeFaceNormals(); var geometry = object.children[0].geometry; console.log(geometry); THREE.GeometryUtils.center(geometry); geometry.dynamic = true; var material = new THREE.MeshLambertMaterial({color: 0xffffff, shading: THREE.FlatShading, vertexColors: THREE.VertexColors }); mesh = new THREE.Mesh(geometry, material); model = mesh; // model = object; scene.add( model ); } ); // RENDERER renderer = new THREE.WebGLRenderer(); renderer.setSize( 400, 700 ); $(this.el).find('.obj').append( renderer.domElement ); this.animate(); }, Here is how I create the instances var morphableBody = new BodyShapeView({ el: $("#morphable-body") }); var bodyShapeView = new BodyShapeView({ el: $("#mean-body") }); Any help would be really appreciated. Thanks in advance.

    Read the article

  • jquery.ui.draggable.js and jquery.ui.widget.js conflict

    - by Daniel S
    hello I had a working application, which uses a jquery ui dialog. I wanted to make the dialog draggable. As far as I know the only thing needed is the jquery.ui.draggable.js script. So I added it to the scripts I am using, but know I get the following error (as shown in the firebug console): base is not a constructor The relevante line in jquery.ui.widget.js is: var basePrototype = new base(); This is how I am adding all the scripts: <script type="text/javascript" src="/media/development-bundle/jquery-1.4.2.js"></script> <script type="text/javascript" src="/media/development-bundle/ui/jquery.ui.core.js"></script> <script type="text/javascript" src="/media/development-bundle/ui/jquery.ui.widget.js"></script> <script type="text/javascript" src="/media/development-bundle/ui/jquery.ui.draggable.js"></script> <script type="text/javascript" src="/media/development-bundle/ui/jquery.ui.position.js"></script> <script type="text/javascript" src="/media/development-bundle/ui/jquery.ui.autocomplete.js"></script> <script type="text/javascript" src="/media/development-bundle/ui/jquery.ui.dialog.js"></script> Am I doing something wrong? or is this a problem with jquery? Thanks in advance for any help

    Read the article

  • node.js simply does not run

    - by user309641
    I installed and ran node.js just fine on my mac, but even if I do this on windows chdir c:\testfolder node example.js then I get this error: node.js:201 throw e; // process.nextTick error, or 'error' event on first tick Error: Cannot find module 'c:\testfolder\example.js' at Function._resolveFilename <module.js:322:11> at Function._load <module.js:299:25> at Array.0 <module.js:499:10> at EventEmitter._tickCallback <node.js:192:40> I'm only even trying to run the example code on the nodejs website: var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/');

    Read the article

  • Node.js on via DynDNS

    - by Azincourt
    I have never used Node.js but since I am developing a browsergame that needs (almost) "realtime" communication, I am planning on using Node.js for this. To get started, I wanted to use a home server (normal computer) that is conntected to a dynamic IP via DynDNS. Are there the disadvantages using such a setting? What is the best way in combination with Node.js to store game status for a online game session?

    Read the article

  • Node.js apps and wordpress on the same vps

    - by Msencenb
    So currently my linode (ubuntu 11.10) serves up three node.js apps for me using connect's vhost middleware listening on port 80. Here is an example of how vhost sets up a domain: var portfolio = require('./bootstrap-portfolio/lib/app.js'); var server = express(); server.use(express.vhost('sencedev.com',portfolio)); server.use(express.vhost('www.sencedev.com',portfolio)); server.listen(80); However I would now like to add a wordpress installation to my vps as well. In the past for me this has meant a traditional apache installation; however I'm a bit unsure of how node.js + a different webserver (apache or nginx) should interact. Any thoughts on how I should approach hosting wordpress + node.js on the same box?

    Read the article

  • Connection timed out on Node.js app running under CentOS

    - by ss1271
    I followed this tutorial to create a simple node.js app on my CentOS: the node.js version is: $ node -v v0.10.28 Here's my app.js: // Include http module, var http = require("http"), // And url module, which is very helpful in parsing request parameters. url = require("url"); // show message at console console.log('Node.js app is running.'); // Create the server. http.createServer(function (request, response) { request.resume(); // Attach listener on end event. request.on("end", function () { // Parse the request for arguments and store them in _get variable. // This function parses the url from request and returns object representation. var _get = url.parse(request.url, true).query; // Write headers to the response. response.writeHead(200, { 'Content-Type': 'text/plain' }); // Send data and end response. response.end('Here is your data: ' + _get['data']); }); // Listen on the 8080 port. }).listen(8080); However, when I uploaded this app onto my remote server (assume the address is 123.456.78.9), I couldn't get access to it on my browser http://123.456.78.9:8080/?data=123 The browser returned Error code: ERR_CONNECTION_TIMED_OUT. I tried the same app.js code which runs fine on my local machine, is there anything I am missing? I tried to ping the server and its address was reachable. Thanks.

    Read the article

  • node.js server not running

    - by CMDadabo
    I am trying to learn node.js, but I'm having trouble getting the simple server to run on localhost:8888. Here is the code for server.js: var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); }).listen(8888); server.js runs without errors, and trying netstat -an | grep 8888 from terminal returns tcp4 0 0 *.8888 *.* LISTEN However, when I go to localhost:8888 in a browser, it says that it cannot be found. I've looked at all the related questions, and nothing has worked so far. I've tried different ports, etc. I know that my router blocks incoming traffic on port 8888, but shouldn't that not matter if I'm trying to access it locally? I've run tomcat servers on this port before, for example. Thanks so much for your help! node.js version: v0.6.15 OS: Mac OS 10.6.8

    Read the article

  • Node.js Adventure - Storage Services and Service Runtime

    - by Shaun
    When I described on how to host a Node.js application on Windows Azure, one of questions might be raised about how to consume the vary Windows Azure services, such as the storage, service bus, access control, etc.. Interact with windows azure services is available in Node.js through the Windows Azure Node.js SDK, which is a module available in NPM. In this post I would like to describe on how to use Windows Azure Storage (a.k.a. WAS) as well as the service runtime.   Consume Windows Azure Storage Let’s firstly have a look on how to consume WAS through Node.js. As we know in the previous post we can host Node.js application on Windows Azure Web Site (a.k.a. WAWS) as well as Windows Azure Cloud Service (a.k.a. WACS). In theory, WAWS is also built on top of WACS worker roles with some more features. Hence in this post I will only demonstrate for hosting in WACS worker role. The Node.js code can be used when consuming WAS when hosted on WAWS. But since there’s no roles in WAWS, the code for consuming service runtime mentioned in the next section cannot be used for WAWS node application. We can use the solution that I created in my last post. Alternatively we can create a new windows azure project in Visual Studio with a worker role, add the “node.exe” and “index.js” and install “express” and “node-sqlserver” modules, make all files as “Copy always”. In order to use windows azure services we need to have Windows Azure Node.js SDK, as knows as a module named “azure” which can be installed through NPM. Once we downloaded and installed, we need to include them in our worker role project and make them as “Copy always”. You can use my “Copy all always” tool mentioned in my last post to update the currently worker role project file. You can also find the source code of this tool here. The source code of Windows Azure SDK for Node.js can be found in its GitHub page. It contains two parts. One is a CLI tool which provides a cross platform command line package for Mac and Linux to manage WAWS and Windows Azure Virtual Machines (a.k.a. WAVM). The other is a library for managing and consuming vary windows azure services includes tables, blobs, queues, service bus and the service runtime. I will not cover all of them but will only demonstrate on how to use tables and service runtime information in this post. You can find the full document of this SDK here. Back to Visual Studio and open the “index.js”, let’s continue our application from the last post, which was working against Windows Azure SQL Database (a.k.a. WASD). The code should looks like this. 1: var express = require("express"); 2: var sql = require("node-sqlserver"); 3:  4: var connectionString = "Driver={SQL Server Native Client 10.0};Server=tcp:ac6271ya9e.database.windows.net,1433;Database=synctile;Uid=shaunxu@ac6271ya9e;Pwd={PASSWORD};Encrypt=yes;Connection Timeout=30;"; 5: var port = 80; 6:  7: var app = express(); 8:  9: app.configure(function () { 10: app.use(express.bodyParser()); 11: }); 12:  13: app.get("/", function (req, res) { 14: sql.open(connectionString, function (err, conn) { 15: if (err) { 16: console.log(err); 17: res.send(500, "Cannot open connection."); 18: } 19: else { 20: conn.queryRaw("SELECT * FROM [Resource]", function (err, results) { 21: if (err) { 22: console.log(err); 23: res.send(500, "Cannot retrieve records."); 24: } 25: else { 26: res.json(results); 27: } 28: }); 29: } 30: }); 31: }); 32:  33: app.get("/text/:key/:culture", function (req, res) { 34: sql.open(connectionString, function (err, conn) { 35: if (err) { 36: console.log(err); 37: res.send(500, "Cannot open connection."); 38: } 39: else { 40: var key = req.params.key; 41: var culture = req.params.culture; 42: var command = "SELECT * FROM [Resource] WHERE [Key] = '" + key + "' AND [Culture] = '" + culture + "'"; 43: conn.queryRaw(command, function (err, results) { 44: if (err) { 45: console.log(err); 46: res.send(500, "Cannot retrieve records."); 47: } 48: else { 49: res.json(results); 50: } 51: }); 52: } 53: }); 54: }); 55:  56: app.get("/sproc/:key/:culture", function (req, res) { 57: sql.open(connectionString, function (err, conn) { 58: if (err) { 59: console.log(err); 60: res.send(500, "Cannot open connection."); 61: } 62: else { 63: var key = req.params.key; 64: var culture = req.params.culture; 65: var command = "EXEC GetItem '" + key + "', '" + culture + "'"; 66: conn.queryRaw(command, function (err, results) { 67: if (err) { 68: console.log(err); 69: res.send(500, "Cannot retrieve records."); 70: } 71: else { 72: res.json(results); 73: } 74: }); 75: } 76: }); 77: }); 78:  79: app.post("/new", function (req, res) { 80: var key = req.body.key; 81: var culture = req.body.culture; 82: var val = req.body.val; 83:  84: sql.open(connectionString, function (err, conn) { 85: if (err) { 86: console.log(err); 87: res.send(500, "Cannot open connection."); 88: } 89: else { 90: var command = "INSERT INTO [Resource] VALUES ('" + key + "', '" + culture + "', N'" + val + "')"; 91: conn.queryRaw(command, function (err, results) { 92: if (err) { 93: console.log(err); 94: res.send(500, "Cannot retrieve records."); 95: } 96: else { 97: res.send(200, "Inserted Successful"); 98: } 99: }); 100: } 101: }); 102: }); 103:  104: app.listen(port); Now let’s create a new function, copy the records from WASD to table service. 1. Delete the table named “resource”. 2. Create a new table named “resource”. These 2 steps ensures that we have an empty table. 3. Load all records from the “resource” table in WASD. 4. For each records loaded from WASD, insert them into the table one by one. 5. Prompt to user when finished. In order to use table service we need the storage account and key, which can be found from the developer portal. Just select the storage account and click the Manage Keys button. Then create two local variants in our Node.js application for the storage account name and key. Since we need to use WAS we need to import the azure module. Also I created another variant stored the table name. In order to work with table service I need to create the storage client for table service. This is very similar as the Windows Azure SDK for .NET. As the code below I created a new variant named “client” and use “createTableService”, specified my storage account name and key. 1: var azure = require("azure"); 2: var storageAccountName = "synctile"; 3: var storageAccountKey = "/cOy9L7xysXOgPYU9FjDvjrRAhaMX/5tnOpcjqloPNDJYucbgTy7MOrAW7CbUg6PjaDdmyl+6pkwUnKETsPVNw=="; 4: var tableName = "resource"; 5: var client = azure.createTableService(storageAccountName, storageAccountKey); Now create a new function for URL “/was/init” so that we can trigger it through browser. Then in this function we will firstly load all records from WASD. 1: app.get("/was/init", function (req, res) { 2: // load all records from windows azure sql database 3: sql.open(connectionString, function (err, conn) { 4: if (err) { 5: console.log(err); 6: res.send(500, "Cannot open connection."); 7: } 8: else { 9: conn.queryRaw("SELECT * FROM [Resource]", function (err, results) { 10: if (err) { 11: console.log(err); 12: res.send(500, "Cannot retrieve records."); 13: } 14: else { 15: if (results.rows.length > 0) { 16: // begin to transform the records into table service 17: } 18: } 19: }); 20: } 21: }); 22: }); When we succeed loaded all records we can start to transform them into table service. First I need to recreate the table in table service. This can be done by deleting and creating the table through table client I had just created previously. 1: app.get("/was/init", function (req, res) { 2: // load all records from windows azure sql database 3: sql.open(connectionString, function (err, conn) { 4: if (err) { 5: console.log(err); 6: res.send(500, "Cannot open connection."); 7: } 8: else { 9: conn.queryRaw("SELECT * FROM [Resource]", function (err, results) { 10: if (err) { 11: console.log(err); 12: res.send(500, "Cannot retrieve records."); 13: } 14: else { 15: if (results.rows.length > 0) { 16: // begin to transform the records into table service 17: // recreate the table named 'resource' 18: client.deleteTable(tableName, function (error) { 19: client.createTableIfNotExists(tableName, function (error) { 20: if (error) { 21: error["target"] = "createTableIfNotExists"; 22: res.send(500, error); 23: } 24: else { 25: // transform the records 26: } 27: }); 28: }); 29: } 30: } 31: }); 32: } 33: }); 34: }); As you can see, the azure SDK provide its methods in callback pattern. In fact, almost all modules in Node.js use the callback pattern. For example, when I deleted a table I invoked “deleteTable” method, provided the name of the table and a callback function which will be performed when the table had been deleted or failed. Underlying, the azure module will perform the table deletion operation in POSIX async threads pool asynchronously. And once it’s done the callback function will be performed. This is the reason we need to nest the table creation code inside the deletion function. If we perform the table creation code after the deletion code then they will be invoked in parallel. Next, for each records in WASD I created an entity and then insert into the table service. Finally I send the response to the browser. Can you find a bug in the code below? I will describe it later in this post. 1: app.get("/was/init", function (req, res) { 2: // load all records from windows azure sql database 3: sql.open(connectionString, function (err, conn) { 4: if (err) { 5: console.log(err); 6: res.send(500, "Cannot open connection."); 7: } 8: else { 9: conn.queryRaw("SELECT * FROM [Resource]", function (err, results) { 10: if (err) { 11: console.log(err); 12: res.send(500, "Cannot retrieve records."); 13: } 14: else { 15: if (results.rows.length > 0) { 16: // begin to transform the records into table service 17: // recreate the table named 'resource' 18: client.deleteTable(tableName, function (error) { 19: client.createTableIfNotExists(tableName, function (error) { 20: if (error) { 21: error["target"] = "createTableIfNotExists"; 22: res.send(500, error); 23: } 24: else { 25: // transform the records 26: for (var i = 0; i < results.rows.length; i++) { 27: var entity = { 28: "PartitionKey": results.rows[i][1], 29: "RowKey": results.rows[i][0], 30: "Value": results.rows[i][2] 31: }; 32: client.insertEntity(tableName, entity, function (error) { 33: if (error) { 34: error["target"] = "insertEntity"; 35: res.send(500, error); 36: } 37: else { 38: console.log("entity inserted"); 39: } 40: }); 41: } 42: // send the 43: console.log("all done"); 44: res.send(200, "All done!"); 45: } 46: }); 47: }); 48: } 49: } 50: }); 51: } 52: }); 53: }); Now we can publish it to the cloud and have a try. But normally we’d better test it at the local emulator first. In Node.js SDK there are three build-in properties which provides the account name, key and host address for local storage emulator. We can use them to initialize our table service client. We also need to change the SQL connection string to let it use my local database. The code will be changed as below. 1: // windows azure sql database 2: //var connectionString = "Driver={SQL Server Native Client 10.0};Server=tcp:ac6271ya9e.database.windows.net,1433;Database=synctile;Uid=shaunxu@ac6271ya9e;Pwd=eszqu94XZY;Encrypt=yes;Connection Timeout=30;"; 3: // sql server 4: var connectionString = "Driver={SQL Server Native Client 11.0};Server={.};Database={Caspar};Trusted_Connection={Yes};"; 5:  6: var azure = require("azure"); 7: var storageAccountName = "synctile"; 8: var storageAccountKey = "/cOy9L7xysXOgPYU9FjDvjrRAhaMX/5tnOpcjqloPNDJYucbgTy7MOrAW7CbUg6PjaDdmyl+6pkwUnKETsPVNw=="; 9: var tableName = "resource"; 10: // windows azure storage 11: //var client = azure.createTableService(storageAccountName, storageAccountKey); 12: // local storage emulator 13: var client = azure.createTableService(azure.ServiceClient.DEVSTORE_STORAGE_ACCOUNT, azure.ServiceClient.DEVSTORE_STORAGE_ACCESS_KEY, azure.ServiceClient.DEVSTORE_TABLE_HOST); Now let’s run the application and navigate to “localhost:12345/was/init” as I hosted it on port 12345. We can find it transformed the data from my local database to local table service. Everything looks fine. But there is a bug in my code. If we have a look on the Node.js command window we will find that it sent response before all records had been inserted, which is not what I expected. The reason is that, as I mentioned before, Node.js perform all IO operations in non-blocking model. When we inserted the records we executed the table service insert method in parallel, and the operation of sending response was also executed in parallel, even though I wrote it at the end of my logic. The correct logic should be, when all entities had been copied to table service with no error, then I will send response to the browser, otherwise I should send error message to the browser. To do so I need to import another module named “async”, which helps us to coordinate our asynchronous code. Install the module and import it at the beginning of the code. Then we can use its “forEach” method for the asynchronous code of inserting table entities. The first argument of “forEach” is the array that will be performed. The second argument is the operation for each items in the array. And the third argument will be invoked then all items had been performed or any errors occurred. Here we can send our response to browser. 1: app.get("/was/init", function (req, res) { 2: // load all records from windows azure sql database 3: sql.open(connectionString, function (err, conn) { 4: if (err) { 5: console.log(err); 6: res.send(500, "Cannot open connection."); 7: } 8: else { 9: conn.queryRaw("SELECT * FROM [Resource]", function (err, results) { 10: if (err) { 11: console.log(err); 12: res.send(500, "Cannot retrieve records."); 13: } 14: else { 15: if (results.rows.length > 0) { 16: // begin to transform the records into table service 17: // recreate the table named 'resource' 18: client.deleteTable(tableName, function (error) { 19: client.createTableIfNotExists(tableName, function (error) { 20: if (error) { 21: error["target"] = "createTableIfNotExists"; 22: res.send(500, error); 23: } 24: else { 25: async.forEach(results.rows, 26: // transform the records 27: function (row, callback) { 28: var entity = { 29: "PartitionKey": row[1], 30: "RowKey": row[0], 31: "Value": row[2] 32: }; 33: client.insertEntity(tableName, entity, function (error) { 34: if (error) { 35: callback(error); 36: } 37: else { 38: console.log("entity inserted."); 39: callback(null); 40: } 41: }); 42: }, 43: // send reponse 44: function (error) { 45: if (error) { 46: error["target"] = "insertEntity"; 47: res.send(500, error); 48: } 49: else { 50: console.log("all done"); 51: res.send(200, "All done!"); 52: } 53: } 54: ); 55: } 56: }); 57: }); 58: } 59: } 60: }); 61: } 62: }); 63: }); Run it locally and now we can find the response was sent after all entities had been inserted. Query entities against table service is simple as well. Just use the “queryEntity” method from the table service client and providing the partition key and row key. We can also provide a complex query criteria as well, for example the code here. In the code below I queried an entity by the partition key and row key, and return the proper localization value in response. 1: app.get("/was/:key/:culture", function (req, res) { 2: var key = req.params.key; 3: var culture = req.params.culture; 4: client.queryEntity(tableName, culture, key, function (error, entity) { 5: if (error) { 6: res.send(500, error); 7: } 8: else { 9: res.json(entity); 10: } 11: }); 12: }); And then tested it on local emulator. Finally if we want to publish this application to the cloud we should change the database connection string and storage account. For more information about how to consume blob and queue service, as well as the service bus please refer to the MSDN page.   Consume Service Runtime As I mentioned above, before we published our application to the cloud we need to change the connection string and account information in our code. But if you had played with WACS you should have known that the service runtime provides the ability to retrieve configuration settings, endpoints and local resource information at runtime. Which means we can have these values defined in CSCFG and CSDEF files and then the runtime should be able to retrieve the proper values. For example we can add some role settings though the property window of the role, specify the connection string and storage account for cloud and local. And the can also use the endpoint which defined in role environment to our Node.js application. In Node.js SDK we can get an object from “azure.RoleEnvironment”, which provides the functionalities to retrieve the configuration settings and endpoints, etc.. In the code below I defined the connection string variants and then use the SDK to retrieve and initialize the table client. 1: var connectionString = ""; 2: var storageAccountName = ""; 3: var storageAccountKey = ""; 4: var tableName = ""; 5: var client; 6:  7: azure.RoleEnvironment.getConfigurationSettings(function (error, settings) { 8: if (error) { 9: console.log("ERROR: getConfigurationSettings"); 10: console.log(JSON.stringify(error)); 11: } 12: else { 13: console.log(JSON.stringify(settings)); 14: connectionString = settings["SqlConnectionString"]; 15: storageAccountName = settings["StorageAccountName"]; 16: storageAccountKey = settings["StorageAccountKey"]; 17: tableName = settings["TableName"]; 18:  19: console.log("connectionString = %s", connectionString); 20: console.log("storageAccountName = %s", storageAccountName); 21: console.log("storageAccountKey = %s", storageAccountKey); 22: console.log("tableName = %s", tableName); 23:  24: client = azure.createTableService(storageAccountName, storageAccountKey); 25: } 26: }); In this way we don’t need to amend the code for the configurations between local and cloud environment since the service runtime will take care of it. At the end of the code we will listen the application on the port retrieved from SDK as well. 1: azure.RoleEnvironment.getCurrentRoleInstance(function (error, instance) { 2: if (error) { 3: console.log("ERROR: getCurrentRoleInstance"); 4: console.log(JSON.stringify(error)); 5: } 6: else { 7: console.log(JSON.stringify(instance)); 8: if (instance["endpoints"] && instance["endpoints"]["nodejs"]) { 9: var endpoint = instance["endpoints"]["nodejs"]; 10: app.listen(endpoint["port"]); 11: } 12: else { 13: app.listen(8080); 14: } 15: } 16: }); But if we tested the application right now we will find that it cannot retrieve any values from service runtime. This is because by default, the entry point of this role was defined to the worker role class. In windows azure environment the service runtime will open a named pipeline to the entry point instance, so that it can connect to the runtime and retrieve values. But in this case, since the entry point was worker role and the Node.js was opened inside the role, the named pipeline was established between our worker role class and service runtime, so our Node.js application cannot use it. To fix this problem we need to open the CSDEF file under the azure project, add a new element named Runtime. Then add an element named EntryPoint which specify the Node.js command line. So that the Node.js application will have the connection to service runtime, then it’s able to read the configurations. Start the Node.js at local emulator we can find it retrieved the connections, storage account for local. And if we publish our application to azure then it works with WASD and storage service through the configurations for cloud.   Summary In this post I demonstrated how to use Windows Azure SDK for Node.js to interact with storage service, especially the table service. I also demonstrated on how to use WACS service runtime, how to retrieve the configuration settings and the endpoint information. And in order to make the service runtime available to my Node.js application I need to create an entry point element in CSDEF file and set “node.exe” as the entry point. I used five posts to introduce and demonstrate on how to run a Node.js application on Windows platform, how to use Windows Azure Web Site and Windows Azure Cloud Service worker role to host our Node.js application. I also described how to work with other services provided by Windows Azure platform through Windows Azure SDK for Node.js. Node.js is a very new and young network application platform. But since it’s very simple and easy to learn and deploy, as well as, it utilizes single thread non-blocking IO model, Node.js became more and more popular on web application and web service development especially for those IO sensitive projects. And as Node.js is very good at scaling-out, it’s more useful on cloud computing platform. Use Node.js on Windows platform is new, too. The modules for SQL database and Windows Azure SDK are still under development and enhancement. It doesn’t support SQL parameter in “node-sqlserver”. It does support using storage connection string to create the storage client in “azure”. But Microsoft is working on make them easier to use, working on add more features and functionalities.   PS, you can download the source code here. You can download the source code of my “Copy all always” tool here.   Hope this helps, Shaun All documents and related graphics, codes are provided "AS IS" without warranty of any kind. Copyright © Shaun Ziyan Xu. This work is licensed under the Creative Commons License.

    Read the article

  • Rendering Flickr Cats Via Backbone.js

    - by Geertjan
    Create a JavaScript file and refer to it inside an HTML file. Then put this into the JavaScript file: (function($) {     var CatCollection = Backbone.Collection.extend({         url: 'http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?',         parse: function(response) {             return response.items;         }     });     var CatView = Backbone.View.extend({         el: $('body'),         initialize: function() {             _.bindAll(this, 'render');             carCollectionInstance.fetch({                 success: function(response, xhr) {                     catView.render();                 }             });         },         render: function() {             $(this.el).append("<ul></ul>");             for (var i = 0; i < carCollectionInstance.length; i++) {                 $('ul', this.el).append("<li>" + i + carCollectionInstance.models[i].get("description") + "</li>");             }         }     });     var carCollectionInstance = new CatCollection();     var catView = new CatView(); })(jQuery); Apologies for any errors or misused idioms. It's my second day with Backbone.js, in fact, my second day with JavaScript. I haven't seen anywhere online so far where an example such as the above is found, though plenty that do kind of or pieces of the above, or explain in text, without an actual full example. The next step, and the only reason for the above experiment, is to create some JPA entities and expose them via RESTful webservices created on EJB methods, for consumption into an HTML5 application via a Backbone.js script very similar to the above. 

    Read the article

  • Can't run node.js script on server reboot

    - by webstyle
    I need to listen events on port 3240 and I'm using node.js for that purpose. I need to execute my script with forever tool. I also need to run forever on server reboot. When I run forever glh.js everything works: forever list says there is a running process. But when I'm trying to run forever on server reboot I can't get it working. I've created a file in /etc/init.d with the following content: #!/bin/bash /var/www/yan/data/gitlabhook/runglh.sh &>/var/www/yan/data/gitlabhook/runglh.log When I reboot the server, the output log is the following (the same as when I run it manually via console): info: Forever processing file: glh.js But in this case forever doesn't start a process. forever list outputs: info: No forever processes running

    Read the article

  • How to filter Backbone.js Collection and Rerender App View?

    - by Jeremy H.
    Is is a total Backbone.js noob question. I am working off of the ToDo Backbone.js example trying to build out a fairly simple single app interface. While the todo project is more about user input, this app is more about filtering the data based on the user options (click events). I am completely new to Backbone.js and Mongoose and have been unable to find a good example of what I am trying to do. I have been able to get my api to pull the data from the MongoDB collection and drop it into the Backbone.js collection which renders it in the app. What I cannot for the life of me figure out how to do is filter that data and re-render the app view. I am trying to filter by the "type" field in the document. Here is my script: (I am totally aware of some major refactoring needed, I am just rapid prototyping a concept.) $(function() { window.Job = Backbone.Model.extend({ idAttribute: "_id", defaults: function() { return { attachments: false } } }); window.JobsList = Backbone.Collection.extend({ model: Job, url: '/api/jobs', leads: function() { return this.filter(function(job){ return job.get('type') == "Lead"; }); } }); window.Jobs = new JobsList; window.JobView = Backbone.View.extend({ tagName: "div", className: "item", template: _.template($('#item-template').html()), initialize: function() { this.model.bind('change', this.render, this); this.model.bind('destroy', this.remove, this); }, render: function() { $(this.el).html(this.template(this.model.toJSON())); this.setText(); return this; }, setText: function() { var month=new Array(); month[0]="Jan"; month[1]="Feb"; month[2]="Mar"; month[3]="Apr"; month[4]="May"; month[5]="Jun"; month[6]="Jul"; month[7]="Aug"; month[8]="Sep"; month[9]="Oct"; month[10]="Nov"; month[11]="Dec"; var title = this.model.get('title'); var description = this.model.get('description'); var datemonth = this.model.get('datem'); var dateday = this.model.get('dated'); var jobtype = this.model.get('type'); var jobstatus = this.model.get('status'); var amount = this.model.get('amount'); var paymentstatus = this.model.get('paymentstatus') var type = this.$('.status .jobtype'); var status = this.$('.status .jobstatus'); this.$('.title a').text(title); this.$('.description').text(description); this.$('.date .month').text(month[datemonth]); this.$('.date .day').text(dateday); type.text(jobtype); status.text(jobstatus); if(amount > 0) this.$('.paymentamount').text(amount) if(paymentstatus) this.$('.paymentstatus').text(paymentstatus) if(jobstatus === 'New') { status.addClass('new'); } else if (jobstatus === 'Past Due') { status.addClass('pastdue') }; if(jobtype === 'Lead') { type.addClass('lead'); } else if (jobtype === '') { type.addClass(''); }; }, remove: function() { $(this.el).remove(); }, clear: function() { this.model.destroy(); } }); window.AppView = Backbone.View.extend({ el: $("#main"), events: { "click #leads .highlight" : "filterLeads" }, initialize: function() { Jobs.bind('add', this.addOne, this); Jobs.bind('reset', this.addAll, this); Jobs.bind('all', this.render, this); Jobs.fetch(); }, addOne: function(job) { var view = new JobView({model: job}); this.$("#activitystream").append(view.render().el); }, addAll: function() { Jobs.each(this.addOne); }, filterLeads: function() { // left here, this event fires but i need to figure out how to filter the activity list. } }); window.App = new AppView; });

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >