Search Results

Search found 129 results on 6 pages for 'knockout 2 0'.

Page 1/6 | 1 2 3 4 5 6  | Next Page >

  • Knockout.js mapping plugin with require.js

    - by Ravi
    What is the standard way of loading mapping plugin in require.js ? Below is my config.js (require.js config file) require.config({ // Initialize the application with the main application file. deps:["app"], paths:{ // JavaScript folders. libs:"lib", plugins:"lib/plugin", templates:"../templates", // Libraries. jquery:"lib/jquery-1.7.2.min", underscore:"lib/lodash", text:'text', order:'order', knockout:"lib/knockout", knockoutmapping:"lib/plugin/knockout-mapping" }, shim:{ underscore:{ exports:'_' }, knockout:{ deps:["jquery"], exports:"knockout" } } } In my view model define(['knockout', 'knockoutmapping'], function(ko, mapping) { } However, mapping is not bound to ko.mapping. Any pointers/suggestions would be appreciated. Thanks, Ravi

    Read the article

  • Knockout.js - Filtering, Sorting, and Paging

    - by jtimperley
    Originally posted on: http://geekswithblogs.net/jtimperley/archive/2013/07/28/knockout.js---filtering-sorting-and-paging.aspxKnockout.js is fantastic! Maybe I missed it but it appears to be missing flexible filtering, sorting, and pagination of its grids. This is a summary of my attempt at creating this functionality which has been working out amazingly well for my purposes. Before you continue, this post is not intended to teach you the basics of Knockout. They have already created a fantastic tutorial for this purpose. You'd be wise to review this before you continue. http://learn.knockoutjs.com/ Please view the full source code and functional example on jsFiddle. Below you will find a brief explanation of some of the components. http://jsfiddle.net/JTimperley/pyCTN/13/ First we need to create a model to represent our records. This model is a simple container with defined and guaranteed members. function CustomerModel(data) { if (!data) { data = {}; } var self = this; self.id = data.id; self.name = data.name; self.status = data.status; } Next we need a model to represent the page as a whole with an array of the previously defined records. I have intentionally overlooked the filtering and sorting options for now. Note how the filtering, sorting, and pagination are chained together to accomplish all three goals. This strategy allows each of these pieces to be used selectively based on the page's needs. If you only need sorting, just sort, etc. function CustomerPageModel(data) { if (!data) { data = {}; } var self = this; self.customers = ExtractModels(self, data.customers, CustomerModel); var filters = […]; var sortOptions = […]; self.filter = new FilterModel(filters, self.customers); self.sorter = new SorterModel(sortOptions, self.filter.filteredRecords); self.pager = new PagerModel(self.sorter.orderedRecords); } The code currently supports text box and drop down filters. Text box filters require defining the current 'Value' and the 'RecordValue' function to retrieve the filterable value from the provided record. Drop downs allow defining all possible values, the current option, and the 'RecordValue' as before. Once defining these filters, they are automatically added to the screen and any changes to their values will automatically update the results, causing their sort and pagination to be re-evaluated. var filters = [ { Type: "text", Name: "Name", Value: ko.observable(""), RecordValue: function(record) { return record.name; } }, { Type: "select", Name: "Status", Options: [ GetOption("All", "All", null), GetOption("New", "New", true), GetOption("Recently Modified", "Recently Modified", false) ], CurrentOption: ko.observable(), RecordValue: function(record) { return record.status; } } ]; Sort options are more simplistic and are also automatically added to the screen. Simply provide each option's name and value for the sort drop down as well as function to allow defining how the records are compared. This mechanism can easily be adapted for using table headers as the sort triggers. That strategy hasn't crossed my functionality needs at this point. var sortOptions = [ { Name: "Name", Value: "Name", Sort: function(left, right) { return CompareCaseInsensitive(left.name, right.name); } } ]; Paging options are completely contained by the pager model. Because we will be chaining arrays between our filtering, sorting, and pagination models, the following utility method is used to prevent errors when handing an observable array to another observable array. function GetObservableArray(array) { if (typeof(array) == 'function') { return array; }   return ko.observableArray(array); }

    Read the article

  • Knockout.js nested sortable bindings

    - by user2391998
    I am working with the knockout.js sortable plugin; however, I ran into a problem that I have so far been unable to solve. I have two sortable bindings, one for buckets and another for bucketItems. I am able to reorder bucketItems between buckets and between buckets; however, I am unable to reorder buckets. Would you have any idea why this would be? I am also using nested with bindings, but as far as I can tell, this is not what is causing problems. I would greatly appreciate any insight you have to offer. Thank you so much for your time!

    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

  • Using Knockout.js to bind bootstrap daterange picker and parse span contents

    - by jmkr
    I'm new to knockout and trying to get what should be a simple task up and running. I'm working on an MVC4 .NET app with the intention of binding a date range picker to make ajax requests for updating Highchart graph data. I'm using Dan Grossman's bootstrap-themed date picker and it's been great so far (https://github.com/dangrossman/bootstrap-daterangepicker). The basic goal is to watch the span that this jQuery date ranger picker updates, and then use knockout to pass this value to another part of the app for the ajax request. I've tried everything I can find online.. valueUpdate:change on the span to using some jQuery within knockout to get the same goal done, to using a subscribe function to watch the value of the span before and after the date picker is used. Apparently this uses the jQuery .change() event handler, which is only good on inputs, selects, and textareas.. not spans. Here's the fiddle of what I have so far: http://jsfiddle.net/eyygK/9/ Appreciate any help and input.

    Read the article

  • How could I implement a fuzzy time date replacer using Knockout?

    - by rball
    I'd like to implement what this plugin does using jQuery: https://github.com/rmm5t/jquery-timeago A short description of that plugin: This will turn all abbr elements with a class of timeago and an ISO 8601 timestamp in the title (conforming to the datetime design pattern microformat): <abbr class="timeago" title="2011-12-17T09:24:17Z">December 17, 2011</abbr> Into something like this: <abbr class="timeago" title="December 17, 2011">about 1 day ago</abbr> Except using knockout my markup looks like this: <abbr data-bind="attr: { title: Posted }" class="timeago"></abbr> I think something isn't synced up because nothing is happening even if I put the call to timeago within the viewmodel itself. I'm guessing I need a subscriber that's attached to the observable "Posted" but I'm not sure how to set that up.

    Read the article

  • Problems using the Razor model when creating my knockout ViewModel

    - by Emil Kantis
    I'm having problems with using the Model in a javascript call when setting up my knockout VM.. @model List<AdminGui.Models.Domain> <script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js" type="text/javascript"></script> <script type="text/javascript"> function ViewModel() { var self = this; self.domains = ko.observableArray( ko.utils.arrayMap(@Model, function(item) { return new Domain(item.guid, item.description, item.namespaces); })); } I get a syntax error on @Model in the ko.utils.arrayMap call. I suspect it might be my Razor-fu that is lacking... :)

    Read the article

  • Is there any syntax checker for knockout.js?

    - by YMC
    I like knockout.js, the only problem is Visual Studio knows nothing about this framework, so it does not prevent me from silly things like assigning some value to observable property with '=' operator which makes it regular property, and it's not easy to reveal at compile time and often at runtime even. I wonder is there any syntax checker/highlighter for Visual Studio 2010 that helps me prevent faults like this? What about VS 2011? It might be a great help for developers who are new to knockout. Thanks

    Read the article

  • backbone js or knockout js as a web framework with jquery mobile

    - by Dan
    without trying to cause a mass discussion I would like some advice from the fellow users of stack overflow. I am about to start building a mobile website that gets it data from JSON that comes from a PHP rest api. I have looked into different mobile frameworks and feel that JQM will work best for us as we have the knowledge of jQuery even though a little large. Currently at work however we are using jQuery for all our sites and realise that now we are building a mobile website I need to think about javascript frameworks to move us onto a more MV* approach, which I understand the benefits of and will bring much needed structure to this mobile site and future web applications we may bring. I have made a comparision table where I have managed to bring the selection down to 2 - backbone and knockout. I have been looking around the web and it seems that there is more support for backbone in general and maybe even more support for backbone with JQM. http://jquerymobile.com/test/docs/pages/backbone-require.html One thing I have noticed however is that backbone doesnt support view bindings (declarative approach) whereas knockout does - is this a massive bonus? one of the main reasons for using a mv* for us is to get more structure - so I would like to use the library that will intergrate best with jQuery and especially jQuery mobile. neither of them seem to have that similar syntax... Thanks

    Read the article

  • Replace between 2 items in observableArray - knockout

    - by Yojik
    im tring to Replace between 2 items in observableArray with knockout but something is wrong.. after the replace of the items ,i will change and send the displayOrder property (in both itmems) to the server (or should i take other approach for this) rankDownMessage: function () { console.log("ranking down msg"); var currentItemindex = viewModel.messages.indexOf(this); var nextItemIndex = currentItemindex + 1; viewModel.messages.replace( viewModel.messages()[nextItemIndex], viewModel.messages()[currentItemindex] ); } only the first item changed to the second item but the second item doesnt become the first one

    Read the article

  • How to filter using a dropdown in Knockout

    - by user517406
    I have just started using Knockout and I want to filter my data that I am displaying in my UI by selecting an item from a dropdown. I have got so far, but I cannot get the selected value from my dropdown yet, and then after that I need to actually filter the data displayed based upon that value. Here is my code so far : @model Models.Fixture @{ ViewBag.Title = "Fixtures"; Layout = "~/Areas/Development/Views/Shared/_Layout.cshtml"; } @Scripts.Render("~/bundles/jqueryval") <script type="text/javascript" src="@Url.Content("~/Scripts/knockout-2.1.0.js")"></script> <script type="text/javascript"> function FixturesViewModel() { var self = this; var baseUri = '@ViewBag.ApiUrl'; self.fixtures = ko.observableArray(); self.teams = ko.observableArray(); self.update = function (fixture) { $.ajax({ type: "PUT", url: baseUri + '/' + fixture.Id, data: fixture }); }; self.sortByAwayTeamScore = function () { this.fixtures.sort(function(a, b) { return a.AwayTeamScore < b.AwayTeamScore ? -1 : 1; }); }; self.select = function (team) { }; $.getJSON("/api/fixture", self.fixtures); $.getJSON("/api/team", self.teams); } $(document).ready(function () { ko.applyBindings(new FixturesViewModel()); }); </script> <div class="content"> <div> <table><tr><td><select data-bind="options: teams, optionsText: 'TeamName', optionsCaption: 'Select...', optionsValue: 'TeamId', click: $root.select"> </select></td></tr></table> <table class="details ui-widget-content"> <thead> <tr><td>FixtureId</td><td>Season</td><td>Week</td><td>AwayTeam</td><td><a id="header" data-bind='click: sortByAwayTeamScore'>AwayTeamScore</a></td><td>HomeTeam</td><td>HomeTeamScore</td></tr> </thead> <tbody data-bind="foreach: fixtures"> <tr> <td><span data-bind="text: $data.Id"></span></td> <td><span data-bind="text: $data.Season"></span></td> <td><span data-bind="text: $data.Week"></span></td> <td><span data-bind="text: $data.AwayTeamName"></span></td> <td><input type="text" data-bind="value: $data.AwayTeamScore"/></td> <td><span data-bind="text: $data.HomeTeamName"></span></td> <td><input type="text" data-bind="value: $data.HomeTeamScore"/></td> <td><input type="button" value="Update" data-bind="click: $root.update"/></td> </tr> </tbody> </table> </div> </div> Can anybody please advise on this?

    Read the article

  • update element in knockout template which was changed by 3td party library

    - by yakov
    I have 'div' element (recaptchaDiv) in knockout template which is not bound to any observable field: <div id="recaptchaDiv"></div> On the other hand, I update this 'div' by 3rd party library. In particular, this is google recaptcha. This is my code: Recaptcha.create("[my private key]", "recaptchaDiv", { theme: "clean", callback: Recaptcha.ToTest }); And it doesn't work (I see nothing). What I know: trying on FF console: $("#recaptchaDiv").html() - it shows the expected html code, I just can't see it in the browser What I tried: to move recaptchaDiv outside of the template and it works: I can see the captcha in the browser to bind recaptchaDiv on html property: in the template: <div id="recaptchaDiv" data-bind="html: recaptcha"></div> in the model: Recaptcha.create("[my private key]", "recaptchaDiv", { theme: "clean", callback: Recaptcha.ToTest }); recaptcha($("#recaptchaDiv").html()); and it doesn't work (replacing jquery on document.getElementById doesn't help) Any help will be very much appreciated!!! Thank you in advance.

    Read the article

  • how to reapply knockout binding

    - by MikeW
    Currently I have a knockout binding that stripes rows in a list which works fine ko.bindingHandlers.stripe = { update: function (element, valueAccessor, allBindingsAccessor) { var value = ko.utils.unwrapObservable(valueAccessor()); //creates the dependency var allBindings = allBindingsAccessor(); var even = allBindings.evenClass; var odd = allBindings.oddClass; //update odd rows $(element).children(":nth-child(odd)").addClass(odd).removeClass(even); //update even rows $(element).children(":nth-child(even)").addClass(even).removeClass(odd); ; } } Triggered from <button data-bind="click: addWidget" style="display:none">Add Item</button> The problem I have is when reloading data from the server , I call addWidget() manually in the view model the stripe binding handler is not applied - all rows appear as same color, if I click the html button then the binding happens and stripes appear var ViewModel = function() { self.addWidget(); }); Is it possible to reapply this custom binding manually in js? Thanks Edit: The stripe binding gets applied like so <div data-bind="foreach: widgets, stripe: widgets, evenClass: 'light', oddClass: 'dark'">

    Read the article

  • Variable text in links with knockout

    - by Gepser
    I'm generating a list of links and they have not the same text but I don't know how to put a text with knockout. This is what I have: <a data-bind="attr: { href: 'Controller/Method/' + Id, 'Title': CurrentTask }"> <!-- I need the name of the CurrentTask here--> CurrentTask </a> So, the text I want to show appears only in the "alt" property but not in the text of the link. It works but I need that the name of the CurrentTask be the link and now it's just showing me everything like this: <a href...>CurrentTask</a> <a href...>CurrentTask</a> <a href...>CurrentTask</a> <a href...>CurrentTask</a> and I need this <a href...>I get this data from de controller</a> <a href...>Sometext</a> <a href...>OtherText</a> <a href...>Anything</a>

    Read the article

  • Great Free Courses on Building HTML5 apps using ASP.NET Web API, Knockout.js and jQuery

    - by ScottGu
    Pluralsight has developed some great training courses on the new .NET 4.5 and VS 2012 release, including two fantastic courses from John Papa that cover how to build HTML5 web apps using ASP.NET Web API, Knockout and jQuery: Single Page Apps with HTML5, Web API, Knockout and jQuery Building HTML5 and JavaScript Apps with MVVM and Knockout Free 1-Month Subscription to the Courses Pluralsight is offering a special promotion that allows you to get a free 1-month subscription to watch the above courses at no cost.  There is no obligation to buy anything at the end of the offer and you don’t need to supply a credit card in order to take part in it. To get access to the course you simply follow @pluralsight and @john_papa on Twitter and then visit this page and enter your Twitter name using the form on it.  Pluralsight will then send you a private twitter message containing the access code that you can use to subscribe to the courses (and download the course exercise files).  Once you are subscribed to the course you have one month to watch the course (and you can watch it as many times as you want during the month). Pluralsight is running the promotion through Sept 18th – so sign-up now to get access.  Once you are signed up you then have a month to watch the course. Hope this helps, Scott P.S. And if you are new to Twitter you can also optionally follow me: @scottgu

    Read the article

  • Duplication of code (backend and javascript - knockout)

    - by Michal B.
    We have a new developer in our team. He seems a smart guy (he just came in so I cannot really judge). He started with implementing some small enhancements in the project (MVC3 web application using javascript - jquery and knockout). Let's say we have two values: A - quite complex calculation C - constant B = A + C On the screen there is value B and user can change it (normal texbox). When B changes, A changes as well because C is constant. So there is linear dependency between A and B. Now, all the calculations are done in the backend, but we need to recalculate A as user changes B (in js, I would use knockout). I thought about storing old A and B and when B changes by 10 then we know that new A will be old A + 10. He says this is dirty, because it's duplication of code (we make use of the fact that they are dependent and according to him that should be only in one place in our app). I understand it's not ideal, but making AJAX request after every key press seems a bit too much. It's a really small thing and I would not post if we haven't had long discussion about it. How do you deal with such problems? Also I can imagine that using knockout implies lots of calculations on the client side, which very often leads to duplication of the same calculations from the backend. Does anyone have links to some articles/thoughts on this topic?

    Read the article

  • Knockout with ASP.Net MVC2 - HTML Extension Helpers for input controls

    - by Renso
    Goal: Defining Knockout-style input controls can be tedious and also may be something that you may find obtrusive, mixing your HTML with data bind syntax as well as binding your aspx, ascx files to Knockout. The goal is to make specifying Knockout specific HTML tags easy, seamless really, as well as being able to remove references to Knockout easily. Environment considerations: ASP.Net MVC2 or later Knockoutjs.js How to:     public static class HtmlExtensions     {         public static string DataBoundCheckBox(this HtmlHelper helper, string name, bool isChecked, object htmlAttributes)         {             var builder = new TagBuilder("input");             var dic = new RouteValueDictionary(htmlAttributes) { { "data-bind", String.Format("checked: {0}", name) } };             builder.MergeAttributes(dic);             builder.MergeAttribute("type", @"checkbox");             builder.MergeAttribute("name", name);             builder.MergeAttribute("value", @"true");             if (isChecked)             {                 builder.MergeAttribute("checked", @"checked");             }             return builder.ToString(TagRenderMode.SelfClosing);         }         public static MvcHtmlString DataBoundSelectList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList, String optionLabel)         {             var attrProperties = new StringBuilder();             attrProperties.Append(String.Format("optionsText: '{0}'", name));             if (!String.IsNullOrEmpty(optionLabel)) attrProperties.Append(String.Format(", optionsCaption: '{0}'", optionLabel));             attrProperties.Append(String.Format(", value: {0}", name));             var dic = new RouteValueDictionary { { "data-bind", attrProperties.ToString() } };             return helper.DropDownList(name, selectList, optionLabel, dic);         }         public static MvcHtmlString DataBoundSelectList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList, String optionLabel, object htmlAttributes)         {             var attrProperties = new StringBuilder();             attrProperties.Append(String.Format("optionsText: '{0}'", name));             if (!String.IsNullOrEmpty(optionLabel)) attrProperties.Append(String.Format(", optionsCaption: '{0}'", optionLabel));             attrProperties.Append(String.Format(", value: {0}", name));             var dic = new RouteValueDictionary(htmlAttributes) {{"data-bind", attrProperties}};             return helper.DropDownList(name, selectList, optionLabel, dic);         }         public static String DataBoundSelectList(this HtmlHelper helper, String options, String optionsText, String value)         {             return String.Format("<select data-bind=\"options: {0},optionsText: '{1}',value: {2}\"></select>", options, optionsText, value);         }         public static MvcHtmlString DataBoundTextBox(this HtmlHelper helper, string name, object value, object htmlAttributes)         {             var dic = new RouteValueDictionary(htmlAttributes);             dic.Add("data-bind", String.Format("value: {0}", name));             return helper.TextBox(name, value, dic);         }         public static MvcHtmlString DataBoundTextBox(this HtmlHelper helper, string name, string observable, object value, object htmlAttributes)         {             var dic = new RouteValueDictionary(htmlAttributes);             dic.Add("data-bind", String.Format("value: {0}", observable));             return helper.TextBox(name, value, dic);         }         public static MvcHtmlString DataBoundTextArea(this HtmlHelper helper, string name, string value, int rows, int columns, object htmlAttributes)         {             var dic = new RouteValueDictionary(htmlAttributes);             dic.Add("data-bind", String.Format("value: {0}", name));             return helper.TextArea(name, value, rows, columns, dic);         }         public static MvcHtmlString DataBoundTextArea(this HtmlHelper helper, string name, string observable, string value, int rows, int columns, object htmlAttributes)         {             var dic = new RouteValueDictionary(htmlAttributes);             dic.Add("data-bind", String.Format("value: {0}", observable));             return helper.TextArea(name, value, rows, columns, dic);         }         public static string BuildUrlFromExpression<T>(this HtmlHelper helper, Expression<Action<T>> action)         {             var values = CreateRouteValuesFromExpression(action);             var virtualPath = helper.RouteCollection.GetVirtualPath(helper.ViewContext.RequestContext, values);             if (virtualPath != null)             {                 return virtualPath.VirtualPath;             }             return null;         }         public static string ActionLink<T>(this HtmlHelper helper, Expression<Action<T>> action, string linkText)         {             return helper.ActionLink(action, linkText, null);         }         public static string ActionLink<T>(this HtmlHelper helper, Expression<Action<T>> action, string linkText, object htmlAttributes)         {             var values = CreateRouteValuesFromExpression(action);             var controllerName = (string)values["controller"];             var actionName = (string)values["action"];             values.Remove("controller");             values.Remove("action");             return helper.ActionLink(linkText, actionName, controllerName, values, new RouteValueDictionary(htmlAttributes)).ToHtmlString();         }         public static MvcForm Form<T>(this HtmlHelper helper, Expression<Action<T>> action)         {             return helper.Form(action, FormMethod.Post);         }         public static MvcForm Form<T>(this HtmlHelper helper, Expression<Action<T>> action, FormMethod method)         {             var values = CreateRouteValuesFromExpression(action);             string controllerName = (string)values["controller"];             string actionName = (string)values["action"];             values.Remove("controller");             values.Remove("action");             return helper.BeginForm(actionName, controllerName, values, method);         }         public static MvcForm Form<T>(this HtmlHelper helper, Expression<Action<T>> action, FormMethod method, object htmlAttributes)         {             var values = CreateRouteValuesFromExpression(action);             string controllerName = (string)values["controller"];             string actionName = (string)values["action"];             values.Remove("controller");             values.Remove("action");             return helper.BeginForm(actionName, controllerName, values, method, new RouteValueDictionary(htmlAttributes));         }         public static string VertCheckBox(this HtmlHelper helper, string name, bool isChecked)         {             return helper.CustomCheckBox(name, isChecked, null);         }          public static string CustomCheckBox(this HtmlHelper helper, string name, bool isChecked, object htmlAttributes)         {             TagBuilder builder = new TagBuilder("input");             builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));             builder.MergeAttribute("type", "checkbox");             builder.MergeAttribute("name", name);             builder.MergeAttribute("value", "true");             if (isChecked)             {                 builder.MergeAttribute("checked", "checked");             }             return builder.ToString(TagRenderMode.SelfClosing);         }         public static string Script(this HtmlHelper helper, string script, object scriptAttributes)         {             var pathForCRMScripts = ScriptsController.GetPathForCRMScripts();             if (ScriptOptimizerConfig.EnableMinimizedFileLoad)             {                 string newPathForCRM = pathForCRMScripts + "Min/";                 ScriptsController.ServerPathMapper = new ServerPathMapper();                 string fullPath = ScriptsController.ServerMapPath(newPathForCRM);                 if (!File.Exists(fullPath + script))                     return null;                 if (!Directory.Exists(fullPath))                     return null;                 pathForCRMScripts = newPathForCRM;             }             var builder = new TagBuilder("script");             builder.MergeAttributes(new RouteValueDictionary(scriptAttributes));             builder.MergeAttribute("type", @"text/javascript");             builder.MergeAttribute("src", String.Format("{0}{1}", pathForCRMScripts.Replace("~", String.Empty), script));             return builder.ToString(TagRenderMode.SelfClosing);         }         private static RouteValueDictionary CreateRouteValuesFromExpression<T>(Expression<Action<T>> action)         {             if (action == null)                 throw new InvalidOperationException("Action must be provided");             var body = action.Body as MethodCallExpression;             if (body == null)             {                 throw new InvalidOperationException("Expression must be a method call");             }             if (body.Object != action.Parameters[0])             {                 throw new InvalidOperationException("Method call must target lambda argument");             }             // This will build up a RouteValueDictionary containing the controller name, action name, and any             // parameters passed as part of the "action" parameter.             string name = body.Method.Name;             string controllerName = typeof(T).Name;             if (controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))             {                 controllerName = controllerName.Remove(controllerName.Length - 10, 10);             }             var values = BuildParameterValuesFromExpression(body) ?? new RouteValueDictionary();             values.Add("controller", controllerName);             values.Add("action", name);             return values;         }         private static RouteValueDictionary BuildParameterValuesFromExpression(MethodCallExpression call)         {             // Build up a RouteValueDictionary containing parameter names as keys and parameter values             // as values based on the MethodCallExpression passed in.             var values = new RouteValueDictionary();             ParameterInfo[] parameters = call.Method.GetParameters();             // If the passed in method has no parameters, just return an empty dictionary.             if (parameters.Length == 0)             {                 return values;             }             for (int i = 0; i < parameters.Length; i++)             {                 object parameterValue;                 Expression expression = call.Arguments[i];                 // If the current parameter is a constant, just use its value as the parameter value.                 var constant = expression as ConstantExpression;                 if (constant != null)                 {                     parameterValue = constant.Value;                 }                 else                 {                     // Otherwise, compile and execute the expression and use that as the parameter value.                     var function = Expression.Lambda<Func<object>>(Expression.Convert(expression, typeof(object)),                                                                    new ParameterExpression[0]);                     try                     {                         parameterValue = function.Compile()();                     }                     catch                     {                         parameterValue = null;                     }                 }                 values.Add(parameters[i].Name, parameterValue);             }             return values;         }     }   Some observations: The first two DataBoundSelectList overloaded methods are specifically built to load the data right into the drop down box as part of the HTML response stream rather than let Knockout's engine populate the options client-side. The third overloaded method does it client-side via the viewmodel. The first two overloads can be done when you have no requirement to add complex JSON objects to your lists. Furthermore, why render and parse the JSON object when you can have it all built and rendered server-side like any other list control.

    Read the article

  • knockout.js bind to static data

    - by MatteS
    whats the suggested way to bind to existing static data? I have to include this in the viewmodel because its used in computed values. http://jsfiddle.net/z2ykC/4/ <div id="sum" data-bind="text: sum"> </div> <div class="line"> dynamic: <span data-bind="text: dynamicValue"></span> static: <span data-bind="text: staticValue">312</span> <button data-bind="click: getDataFromServer">get data</button> </div> <div class="line"> dynamic: <span data-bind="text: dynamicValue"></span> static: <span data-bind="text: staticValue">123</span> <button data-bind="click: getDataFromServer">get data</button> </div> ? function SumViewModel(lines){ this.sum = ko.computed(function(){ var value = 0; $.each(lines, function(index, element){ var staticValue = element.staticValue(); if (staticValue) value += staticValue; var dynamicValue = element.dynamicValue(); if (dynamicValue) value += dynamicValue; value += dynamicValue; }); return value; }); } function LineViewModel() { this.randomNumber = function(max) { return Math.floor((Math.random() * max) + 1); }; this.dynamicValue = ko.observable(0); this.staticValue = ko.observable(); this.getDataFromServer = function() { this.dynamicValue(this.randomNumber(300)); }; }; var lines = []; $('.line').each(function(index, element) { var line = new LineViewModel() //line.staticValue(parseInt($('[data-bind*="staticValue"]', element).text())); lines.push(line); ko.applyBindings(line, element); }); var sum = new SumViewModel(lines); ko.applyBindings(sum, $('#sum')[0]);

    Read the article

  • knockout bind text label to dropdown value selected option text

    - by Adam Levitt
    Is there a simple way to bind the textbox of a div to change based on the text value of the selected option in a dropdown on the same page? <div data-bind="text: dropdownValue"></div> <select> <option value="1">Value1</option> <option value="2">Value2</option> </select> Please note, I don't want to put the values into the select element using javascript. I'd like to bind to the value straight from the HTML. I can also include jQuery to make it work.

    Read the article

  • Always require a plugin to be loaded

    - by axon
    I am writing an application with RequireJS and Knockout JS. The application includes an extension to knockout that adds ko.protectedObservable to the main knockout object. I would like this to always be available on the require'd knockout object, and not only when I specify it in the dependencies. I could concat the files together, but that seems that it should be unnecessary. Additionally, I can put knockout-protectedObservable as a dependency for knockout in the requirejs shim configuration, but that just leads to a circular dependency and it all fails to load. Edit: I've solved me issue, but seems hacky, is there a better way? -- Main.html <script type="text/javascript" src="require.js"></script> <script type="text/javascript"> require(['knockout'], function(ko) { require(['knockout-protectedObservable']); }); </script> -- knockout-protectedObservable.js define(['knockout'], function(ko) { ko.protectedObservable = { ... }; });

    Read the article

  • knockout.js with optionsValue and value

    - by Mike Flynn
    Is there a way to keep the value binding to the object, but have the optionsValue be a property on the object. As of now if I specify both, the optionsValue property that is selected will populate the value binding. Id like to keep the object intact in the observable, but specify what value to be set in the select list value. This way a form submit will send the optionsValue I chose. @Html.DropDownListFor(q => q.DivisionId, new SelectList(Enumerable.Empty<string>()), new { data_bind="options: divisions, optionsText: 'Name', optionsValue: 'Id', value: division, optionsCaption: ' - '" }) function AddCrossPoolGameDialog() { var self = this; self.divisions = ko.observableArray([]); self.division = ko.observable(); self.awayDivisionTeams = ko.computed(function () { var division = ko.utils.arrayFirst(self.divisions(), function(item) { return self.division.Name() == item.Name; }); if (division) { return division.DivisionTeamPools; } return []; }); }

    Read the article

  • Kendo UI Mobile with Knockout for Master-Detail Views

    - by Steve Michelotti
    Lately I’ve been playing with Kendo UI Mobile to build iPhone apps. It’s similar to jQuery Mobile in that they are both HTML5/JavaScript based frameworks for buildings mobile apps. The primary thing that drew me to investigate Kendo UI was its innate ability to adaptively render a native looking app based on detecting the device it’s currently running on. In other words, it will render to look like a native iPhone app if it’s running on an iPhone and it will render to look like a native Droid app if it’s running on a Droid. This is in contrast to jQuery Mobile which looks the same on all devices and, therefore, it can never quite look native for whatever device it’s running on. My first impressions of Kendo UI were great. Using HTML5 data-* attributes to define “roles” for UI elements is easy, the rendering looked great, and the basic navigation was simple and intuitive. However, I ran into major confusion when trying to figure out how to “correctly” build master-detail views. Since I was already very family with KnockoutJS, I set out to use that framework in conjunction with Kendo UI Mobile to build the following simple scenario: I wanted to have a simple “Task Manager” application where my first screen just showed a list of tasks like this:   Then clicking on a specific task would navigate to a detail screen that would show all details of the specific task that was selected:   Basic navigation between views in Kendo UI is simple. The href of an <a> tag just needs to specify a hash tag followed by the ID of the view to navigate to as shown in this jsFiddle (notice the href of the <a> tag matches the id of the second view):   Direct link to jsFiddle: here. That is all well and good but the problem I encountered was: how to pass data between the views? Specifically, I need the detail view to display all the details of whichever task was selected. If I was doing this with my typical technique with KnockoutJS, I know exactly what I would do. First I would create a view model that had my collection of tasks and a property for the currently selected task like this: 1: function ViewModel() { 2: var self = this; 3: self.tasks = ko.observableArray(data); 4: self.selectedTask = ko.observable(null); 5: } Then I would bind my list of tasks to the unordered list - I would attach a “click” handler to each item (each <li> in the unordered list) so that it would select the “selectedTask” for the view model. The problem I found is this approach simply wouldn’t work for Kendo UI Mobile. It completely ignored the click handlers that I was trying to attach to the <a> tags – it just wanted to look at the href (at least that’s what I observed). But if I can’t intercept this, then *how* can I pass data or any context to the next view? The only thing I was able to find in the Kendo documentation is that you can pass query string arguments on the view name you’re specifying in the href. This enabled me to do the following: Specify the task ID in each href – something like this: <a href=”#taskDetail?id=3></a> Attach an “init method” (via the “data-show” attribute on the details view) that runs whenever the view is activated Inside this “init method”, grab the task ID passed from the query string to look up the item from my view model’s list of tasks in order to set the selected task I was able to get all that working with about 20 lines of JavaScript as shown in this jsFiddle. If you click on the Results tab, you can navigate between views and see the the detail screen is correctly binding to the selected item:   Direct link to jsFiddle: here.   With all that being done, I was very happy to get it working with the behavior I wanted. However, I have no idea if that is the “correct” way to do it or if there is a “better” way to do it. I know that Kendo UI comes with its own data binding framework but my preference is to be able to use (the well-documented) KnockoutJS since I’m already familiar with that framework rather than having to learn yet another new framework. While I think my solution above is probably “acceptable”, there are still a couple of things that bug me about it. First, it seems odd that I have to loop through my items to *find* my selected item based on the ID that was passed on the query string - normally, with Knockout I can just refer directly to my selected item from where it was used. Second, it didn’t feel exactly right that I had to rely on the “data-show” method of the details view to set my context – normally with Knockout, I could just attach a click handler to the <a> tag that was actually clicked by the user in order to set the “selected item.” I’m not sure if I’m being too picky. I know there are many people that have *way* more expertise in Kendo UI compared to me – I’d be curious to know if there are better ways to achieve the same results.

    Read the article

  • jquery and requirejs and knockout; reference requirejs object from within itself

    - by Thomas
    We use jquery and requirejs to create a 'viewmodel' like this: define('vm.inkoopfactuurAanleveren', ['jquery', 'underscore', 'ko', 'datacontext', 'router', 'messenger', 'config', 'store'], function ($, _, ko, datacontext, router, messenger, config, store) { var isBusy = false, isRefreshing = false, inkoopFactuur = { factuurNummer: ko.observable("AAA") }, activate = function (routeData, callback) { messenger.publish.viewModelActivated({ canleaveCallback: canLeave }); getNewInkoopFactuurAanleveren(callback); var restricteduploader = new qq.FineUploader({ element: $('#restricted-fine-uploader')[0], request: { endpoint: 'api/InkoopFactuurAanleveren', forceMultipart: true }, multiple: false, failedUploadTextDisplay: { mode: 'custom', maxChars: 250, responseProperty: 'error', enableTooltip: true }, text: { uploadButton: 'Click or Drop' }, showMessage: function (message) { $('#restricted-fine-uploader').append('<div class="alert alert-error">' + message + '</div>'); }, debug: true, callbacks: { onComplete: function (id, fileName, responseJSON) { var response = responseJSON; }, } }); }, invokeFunctionIfExists = function (callback) { if (_.isFunction(callback)) { callback(); } }, loaded = function (factuur) { inkoopFactuur = factuur; var ids = config.viewIds; ko.applyBindings(this, getView(ids.inkoopfactuurAanleveren)); /*<----- THIS = OUT OF SCOPE!*/ / }, bind = function () { }, saved = function (success) { var s = success; }, saveCmd = ko.asyncCommand({ execute: function (complete) { $.when(datacontext.saveNewInkoopFactuurAanleveren(inkoopFactuur)) .then(saved).always(complete); return; }, canExecute: function (isExecuting) { return true; } }), getView = function (viewName) { return $(viewName).get(0); }, getNewInkoopFactuurAanleveren = function (callback) { if (!isRefreshing) { isRefreshing = true; $.when(datacontext.getNewInkoopFactuurAanleveren(dataOptions(true))).then(loaded).always(invokeFunctionIfExists(callback)); isRefreshing = false; } }, dataOptions = function (force) { return { results: inkoopFactuur, // filter: sessionFilter, //sortFunction: sort.sessionSort, forceRefresh: force }; }, canLeave = function () { return true; }, forceRefreshCmd = ko.asyncCommand({ execute: function (complete) { //$.when(datacontext.sessions.getSessionsAndAttendance(dataOptions(true))) // .always(complete); complete; } }), init = function () { // activate(); // Bind jQuery delegated events //eventDelegates.sessionsListItem(gotoDetails); //eventDelegates.sessionsFavorite(saveFavorite); // Subscribe to specific changes of observables //addFilterSubscriptions(); }; init(); return { activate: activate, canLeave: canLeave, inkoopFactuur: inkoopFactuur, saveCmd: saveCmd, forceRefreshCmd: forceRefreshCmd, bind: bind, invokeFunctionIfExists: invokeFunctionIfExists }; }); On the line ko.applyBindings(this, getView(ids.inkoopfactuurAanleveren)); in the 'loaded' method the 'this' keyword doens't refer to the 'viewmodel' object. the 'self' keyword seems to refer to a combination on methods found over multiple 'viewmodels'. The saveCmd property is bound through knockout, but gives an error since it cannot be found. How can the ko.applyBindings get the right reference to the viewmodel? In other words, with what do we need to replace the 'this' keyword int he applyBindings. I would imagine you can 'ask' requirejs to give us the ealiers instantiated object with identifier 'vm.inkoopfactuurAanleveren' but I cannot figure out how.

    Read the article

  • why does this knockout method receive a form element instead of the object its nested in?

    - by ladookie
    I have this HTML: <ul class="chat_list" data-bind="foreach: chats"> <li> <div class="chat_response" data-bind="visible: CommentList().length == 0"> <form data-bind="submit: $root.addComment"> <input class="comment_field" placeholder="Comment…" data-bind="value: NewCommentText" /> </form> </div> </li> </ul> and this JavaScript: function ChatListViewModel(chats) { // var self = this; self.chats = ko.observableArray(ko.utils.arrayMap(chats, function (chat) { return { CourseItemDescription: chat.CourseItemDescription, CommentList: ko.observableArray(chat.CommentList), CourseItemID: chat.CourseItemID, UserName: chat.UserName, ChatGroupNumber: chat.ChatGroupNumber, ChatCount: chat.ChatCount, NewCommentText: ko.observable("") }; })); self.newChatText = ko.observable(); self.addComment = function (chat) { var newComment = { CourseItemDescription: chat.NewCommentText(), ParentCourseItemID: chat.CourseItemID, CourseID: $.CourseLogic.dataitem.CourseID, AccountID: $.CourseLogic.dataitem.AccountID, SystemObjectID: $.CourseLogic.dataitem.CommentSystemObjectID, SystemObjectName: "Comments", UserName: chat.UserName }; chat.CommentList.push(newComment); chat.NewCommentText(""); }; } ko.applyBindings(new ChatListViewModel(initialData)); When I go into the debugger it shows that the chat parameter of the addComment() function is a form element instead of a chat object. Why is this happening?

    Read the article

  • How do I convert an AMD module from a singleton to an instance?

    - by Jamie Ide
    I'm trying to convert a working Durandal view model module from a singleton to an instance. The original working version followed this pattern: define(['knockout'], function(ko) { var vm = { activate: activate, companyId: null; company: ko.observable({}) }; return vm; function activate(companyId) { vm.companyId = companyId; //get company data then vm.company(data); } } The new version exports a function so that I get a new instance on every request... define(['knockout'], function(ko) { var vm = function() { activate = activate; companyId = null; company = ko.observable({}); }; return vm; function activate(companyId) { vm.companyId = companyId; //get company data then vm.company(data); } } The error I'm getting is "object function () [...function signature...] has no method company on the line vm.company(data);. What am I doing wrong? Why can I set the property but can't access the knockout observable? How should I refactor the original code so that I get a new instance on every request? My efforts to simplify the code for this question hid the actual problem. My real code was using Q promises and calling two methods with Q.All. Since Q is in the global namespace, it couldn't resolve my viewmodel after converting to a function. Passing the view model to the methods called by Q resolved the problem.

    Read the article

1 2 3 4 5 6  | Next Page >