public Person(string name, string[] children) { Name = Knockout.Observable(name); Children = Knockout.ObservableArray(children); var self = this; AddChild = () => self.Children.Push("New Child"); }
public GiftViewModel(Gift[] gifts) { var self = this; self.Gifts = Knockout.ObservableArray(gifts); self.AddGift = () => self.Gifts.Push(new Gift(name: "", price: 0)); self.RemoveGift = gift => self.Gifts.Remove(gift); self.Save = () => Window.Alert("Could now transmit to server: " + KnockoutUtils.StringifyJson(self.Gifts)); }
public ControlTypesViewModel() { StringValue = Knockout.Observable("Hello"); PasswordValue = Knockout.Observable("mypass"); BooleanValue = Knockout.Observable(true); OptionValues = Knockout.ObservableArray(new[] { "Alpha", "Beta", "Gamma" }); SelectedOptionValue = Knockout.Observable("Gamma"); MultipleSelectedOptionValues = Knockout.ObservableArray(new[] { "Alpha" }); RadioSelectedOptionValue = Knockout.Observable("Beta"); }
public void ToViewModel_Simple_Class() { var model = new SimpleClass { A = 5, B = "test" }; var json = Knockout.ToViewModel(model); Assert.AreEqual("{\"A\":ko.observable(5),\"B\":ko.observable(\"test\")}", json.ToJson()); }
public QuoteDetail Commit() { if (InnerQuoteDetail == null) { return(null); } InnerQuoteDetail.RequestDeliveryBy = Knockout.UnwrapObservable <DateTime>(RequestDeliveryBy); InnerQuoteDetail.SalesRepId = Knockout.UnwrapObservable <EntityReference>(SalesRepId); InnerQuoteDetail.RaisePropertyChanged(""); return(InnerQuoteDetail); }
public void ToViewModel_Mock_Property_Override_Moq() { var model = new Mock <SimpleClass>(); model.Setup(m => m.A).Returns(5); model.Setup(m => m.B).Returns("test"); var json = Knockout.ToViewModel(model.Object); Assert.AreEqual("{\"A\":ko.observable(5),\"B\":ko.observable(\"test\")}", json.ToJson()); }
public override void DumpBody(XmlWriter writer) { writer.WriteElementString("color", Color.ToHtmlHex()); writer.WriteElementString("blur-x", BlurX.ToString()); writer.WriteElementString("blur-y", BlurY.ToString()); writer.WriteElementString("strength", Strength.ToString()); writer.WriteElementString("inner", Inner.ToString()); writer.WriteElementString("knockout", Knockout.ToString()); writer.WriteElementString("composite-source", CompositeSource.ToString()); writer.WriteElementString("passes", Passes.ToString()); }
public ContactViewModel() { ObservableContact contact = new ObservableContact(); Contacts = new EntityDataViewModel(15, typeof(Contact), false); ContactEdit = (Observable <ObservableContact>)ValidatedObservableFactory.ValidatedObservable(contact);//Knockout.Observable<ObservableContact>(new ObservableContact()); ContactEdit.GetValue().OnSaveComplete += ContactViewModel_OnSaveComplete; ErrorMessage = Knockout.Observable <string>(); Contacts.OnDataLoaded.Subscribe(Contacts_OnDataLoaded); ObservableContact.RegisterValidation(Contacts.ValidationBinder); }
public override void Register(string fieldName, ValidationRuleDelegate ruleDelegate) { // Get observable field Dictionary viewModel = Knockout.UnwrapObservable <Dictionary>(_observable); object observableField = viewModel[fieldName]; // Get the rule object rule = ruleDelegate(ValidationRules.CreateRules(), _observable, null); // Register the Validation rule on the observable ((Observable <object>)observableField).Extend((Dictionary)(object)rule); }
public void ToViewModel_Nested_Class() { var model = new NestedClass { Child = new SimpleClass { A = 5, B = "test" }, C = true }; var json = Knockout.ToViewModel(model); Assert.AreEqual("{\"C\":ko.observable(true),\"Child\":{\"A\":ko.observable(5),\"B\":ko.observable(\"test\")}}", json.ToJson()); }
public TestPageViewModel(List <string[]> list) { this.list = list; Messages = Knockout.Observable <string>(""); AddMessage("Query string data parameter:"); // Add parameters foreach (string[] param in list) { AddMessage(String.Format("{0}={1}", param[0], param[1])); } }
public static void Setup() { var viewModel = new GiftViewModel(new[] { new Gift(name: "Tall Hat", price: 39.95), new Gift(name: "Long Cloak", price: 120.00) }); Knockout.ApplyBindings(viewModel); // Activate jQuery Validation var vm = viewModel; jQuery.Select("form", Window.Document).Validate(new ValidationOptions(submitHandler: vm.Save)); }
public CartLineViewModel() { var self = this; self.Category = Knockout.Observable <string>(); self.Product = Knockout.Observable <Product>(); self.Quantity = Knockout.Observable(1); self.Subtotal = Knockout.Computed( () => self.Product.Value != null ? self.Product.Value.Price * int.Parse("0" + self.Quantity.Value, 10) : 0); // Whenever the category changes, reset the product selection self.Category.Subscribe(val => { self.Product.Value = null; }); }
private async Task <Knockout> CreateKnockout(CompetitionStage stage, KnockoutEventTemplate knockoutEventTemplate) { var knockout = Knockout.Create(stage); knockout.MatchFormat = new MatchFormat { ID = (short)knockoutEventTemplate.MatchFormatID }; knockout.MatchCalculationEngineID = knockoutEventTemplate.MatchCalculationEngine; knockout.FixtureCalculationEngineID = knockoutEventTemplate.FixtureCalculationEngine; knockout.KnockoutCalculationEngineID = knockoutEventTemplate.KnockoutCalculationEngine; await this._competitionEventRepository.Save(knockout); return(knockout); }
public static ValidationRules ProductId(ValidationRules rules, object viewModel, object dataContext) { QuoteDetail self = Knockout.UnwrapObservable <QuoteDetail>(viewModel); return(rules .AddRule("Select either a product or provide a product description.", delegate(object value) { // Only a productdescription or productid can be selected string productDescription = Knockout.UnwrapObservable <string>(self.ProductDescription); bool isValid = String.IsNullOrEmpty(productDescription) || (value == null); return isValid; } )); }
public static ValidationRules WriteInProduct(ValidationRules rules, object viewModel, object dataContext) { QuoteDetail self = Knockout.UnwrapObservable <QuoteDetail>(viewModel); return(rules .AddRule("Select either a product or provide a product description.", delegate(object value) { // Only a productdescription or productid can be selected EntityReference productid = Knockout.UnwrapObservable <EntityReference>(self.ProductId); bool isValid = String.IsNullOrEmpty((string)value) || (productid == null); return isValid; } )); }
public ConnectionsViewModel(EntityReference parentRecordId, string[] connectToTypes, int pageSize, string viewFetchXml) { Connections = new EntityDataViewModel(pageSize, typeof(Connection), true); ParentRecordId.SetValue(parentRecordId); _viewFetchXml = viewFetchXml; ObservableConnection connection = new ObservableConnection(connectToTypes); connection.Record2Id.SetValue(parentRecordId); ConnectionEdit = (Observable <ObservableConnection>)ValidatedObservableFactory.ValidatedObservable(connection); Connections.OnDataLoaded.Subscribe(Connections_OnDataLoaded); ConnectionEdit.GetValue().OnSaveComplete += ConnectionsViewModel_OnSaveComplete; ObservableConnection.RegisterValidation(Connections.ValidationBinder); AllowAddNew = Knockout.DependentObservable <bool>(AllowAddNewComputed); }
public static void RegisterViewModel(object viewModel) { jQuery.OnDocumentReady(delegate() { jQuery.Get("../../sparkle_/html/form.templates.htm", delegate(object template) { jQuery.Select("body").Append((string)template); ValidationApi.RegisterExtenders(); // Init settings OrganizationServiceProxy.GetUserSettings(); Knockout.ApplyBindings(viewModel); }); }); }
public ContactsViewModel(EntityReference parentCustomerId, int pageSize) { Contacts = new EntityDataViewModel(pageSize, typeof(Contact), true); ParentCustomerId.SetValue(parentCustomerId); ObservableContact contact = new ObservableContact(); contact.ParentCustomerId.SetValue(parentCustomerId); ContactEdit = (Observable <ObservableContact>)ValidatedObservableFactory.ValidatedObservable(contact); ContactEdit.GetValue().OnSaveComplete += ContactsViewModel_OnSaveComplete; Contacts.OnDataLoaded.Subscribe(Contacts_OnDataLoaded); ObservableContact.RegisterValidation(Contacts.ValidationBinder); AllowAddNew = Knockout.DependentObservable <bool>(AllowAddNewComputed); AllowOpen = Knockout.Observable <bool>(false); Contacts.OnSelectedRowsChanged += Contacts_OnSelectedRowsChanged; }
public MultiSearchViewModel2013() { //OrganizationServiceProxy.WithCredentials = true; DependentObservableOptions <string> throttledSearchTermObservable = new DependentObservableOptions <string>(); throttledSearchTermObservable.Model = this; throttledSearchTermObservable.GetValueFunction = new Func <string>(delegate { return(this.SearchTerm.GetValue()); }); ThrottledSearchTerm = Knockout.DependentObservable <string>(throttledSearchTermObservable).Extend(new Dictionary("throttle", 400)); ThrottledSearchTerm.Subscribe(new Action <string>(delegate(string search) { // Search whilst typing using the throttle extension SearchCommand(); })); // Get Config Dictionary <string, string> dataConfig = PageEx.GetWebResourceData(); // Query the quick search entities QueryQuickSearchEntities(); Dictionary <string, Entity> views = GetViewQueries(); _parser = new QueryParser(); foreach (string typeName in _entityTypeNames) { Entity view = views[typeName]; string fetchXml = view.GetAttributeValueString("fetchxml"); string layoutXml = view.GetAttributeValueString("layoutxml"); // Parse the fetch and layout to get the attributes and columns FetchQuerySettings config = _parser.Parse(fetchXml, layoutXml); config.RecordCount = Knockout.Observable <string>(); config.DataView = new VirtualPagedEntityDataViewModel(25, typeof(Entity), true); config.RecordCount.SetValue(GetResultLabel(config)); Config.Push(config); // Wire up record count change config.DataView.OnPagingInfoChanged.Subscribe(OnPagingInfoChanged(config)); } _parser.QueryDisplayNames(); }
public PagedGridViewModel(Data[] items) { var self = this; Items = Knockout.ObservableArray(items); AddItem = () => self.Items.Push(new Data("New Item", 0, 100)); SortByName = () => self.Items.Sort((a, b) => a.Name.CompareTo(b.Name)); JumpToFirstPage = () => { self.GridViewModel.CurrentPageIndex.Value = 0; }; GridViewModel = new ViewModel <Data>(new Configuration <Data> ( pageSize: 4, data: self.Items, columns: Knockout.ObservableArray(new[] { new Column <Data>("Item Name", "name"), new Column <Data>("Sales Count", "sales"), new Column <Data>("Price", item => "R " + item.Price.ToFixed(2)) } ))); }
public SimpleListViewModel(string[] items) { this.Items = Knockout.ObservableArray(items); this.ItemToAdd = Knockout.Observable(""); var self = this; this.AddItem = () => { if (self.ItemToAdd.Value != "") { // Adds the item. Writing to the "items" observableArray // causes any associated UI to update. self.Items.Push(self.ItemToAdd.Value); // Clears the text box, because it's bound to the // "itemToAdd" observable self.ItemToAdd.Value = ""; } }; }
public static object required(Target target, string overrideMessage) { //add some sub-observables to our observable target.hasError = Knockout.observable <bool>(); target.validationMessage = Knockout.observable <JsString>(); //define a function to do validation JsAction <object> validate = (newValue) => { target.hasError.Value = newValue.As <bool>() ? false : true; target.validationMessage.Value = newValue.As <bool>() ? "" : overrideMessage ?? "This field is required"; }; //initial validation validate(target.Value); //validate whenever the value changes target.subscribe(validate); //return the original observable return(target); }
public ConnectionsViewModel(EntityReference parentRecordId, string[] connectToTypes, int pageSize, FetchQuerySettings view) { Connections = new EntityDataViewModel(pageSize, typeof(Connection), true); if (view != null) { _viewFetchXml = QueryParser.GetFetchXmlParentFilter(view, "record1id"); // Set initial sort _defaultSortCol = new SortCol(view.OrderByAttribute, !view.OrderByDesending); } ParentRecordId.SetValue(parentRecordId); ObservableConnection connection = new ObservableConnection(connectToTypes); connection.Record2Id.SetValue(parentRecordId); ConnectionEdit = (Observable <ObservableConnection>)ValidatedObservableFactory.ValidatedObservable(connection); Connections.OnDataLoaded.Subscribe(Connections_OnDataLoaded); ConnectionEdit.GetValue().OnSaveComplete += ConnectionsViewModel_OnSaveComplete; ObservableConnection.RegisterValidation(Connections.ValidationBinder); AllowAddNew = Knockout.DependentObservable <bool>(AllowAddNewComputed); }
public static void Setup() { var savedLists = new List <TweetGroup> { new TweetGroup( name: Knockout.Observable("Celebrities"), userNames: Knockout.ObservableArray(new[] { "JohnCleese", "MCHammer", "StephenFry", "algore", "StevenSanderson" })), new TweetGroup( name: Knockout.Observable("Microsoft people"), userNames: Knockout.ObservableArray(new[] { "BillGates", "shanselman", "ScottGu" })), new TweetGroup( name: Knockout.Observable("Tech pundits"), userNames: Knockout.ObservableArray(new[] { "Scobleizer", "LeoLaporte", "techcrunch", "BoingBoing", "timoreilly", "codinghorror" })) }; Knockout.ApplyBindings(new TwitterViewModel(savedLists, "Tech pundits")); // Using jQuery for Ajax loading indicator - nothing to do with Knockout var loading = jQuery.Select(".loadingIndicator"); jQueryEx.AjaxPrefilter(options => { options.Global = true; }); jQuery.FromObject(Document.Instance).AjaxStart(() => loading.FadeIn()).AjaxStop(() => loading.FadeOut()); }
public DependentObservable <bool> CanAddNew() { if (_canAddNew == null) { DependentObservableOptions <bool> IsRegisterFormValidDependantProperty = new DependentObservableOptions <bool>(); IsRegisterFormValidDependantProperty.Model = this; IsRegisterFormValidDependantProperty.GetValueFunction = new Func <bool>(delegate { EntityStates state = SelectedContact.GetValue().EntityState.GetValue(); if (state != null) { return(state != EntityStates.Created); } else { return(true); } }); _canAddNew = Knockout.DependentObservable <bool>(IsRegisterFormValidDependantProperty); } return(_canAddNew); }
public CellarApplication() { _pages = Knockout.Observable <int>(0); _pageIndex = Knockout.Observable <int>(0); Wines = Knockout.Observable <IEnumerable <Wine> >(); SelectedWine = Knockout.Observable <Wine>(); CanGoPrevious = Knockout.Computed <bool>(ComputeCanGoPrevious); CanGoNext = Knockout.Computed <bool>(ComputeCanGoNext); ShowSelection = Knockout.Computed <bool>(ComputeShowSelection); Next = delegate() { NextCommand(); }; Previous = delegate() { PreviousCommand(); }; Select = delegate(Wine wine) { SelectCommand(wine); }; LoadWines(); }
public ContactsViewModel(List <Contact> contacts) { var self = this; self.Contacts = Knockout.ObservableArray(KnockoutUtils.ArrayMap( contacts, contact => new Contact( firstName: contact.FirstName, lastName: contact.LastName, phones: Knockout.ObservableArray(contact.Phones.Value)) )); self.AddContact = () => self.Contacts.Push(new Contact( firstName: "", lastName: "", phones: Knockout.ObservableArray <Phone>())); self.RemoveContact = contact => self.Contacts.Remove(contact); self.AddPhone = contact => contact.Phones.Push(new Phone(type: "", number: "")); self.RemovePhone = phone => jQuery.Each(self.Contacts.ToList(), (index, value) => value.Phones.Remove(phone)); self.Save = () => { self.LastSavedJson.Value = Json.Stringify(Knockout.ToObject(self.Contacts), (string[])null, 2); }; self.LastSavedJson = Knockout.Observable(""); }
public void OnSaveChanges() { var saveAs = Window.Prompt("Save User List:", this.EditingList.Name.Value); if (saveAs != null) { var dataToSave = (string[])this.EditingList.UserNames.Value.Slice(0); var existingSavedList = this.FindSavedList(saveAs); if (existingSavedList != null) { // Overwrite existing list existingSavedList.UserNames.Value = dataToSave; } else { // Add new list this.SavedLists.Push(new TweetGroup( name: Knockout.Observable(saveAs), userNames: Knockout.ObservableArray(dataToSave))); } this.EditingList.Name.Value = saveAs; } }
public static ValidationRules FirstName(ValidationRules rules, object viewModel, object dataContext) { Contact self = Knockout.UnwrapObservable <Contact>(viewModel); return(rules .AddRequiredMsg("Enter a first name") .AddRule("Must be less than 200 chars", delegate(object value) { string valueText = (string)value; return (valueText.Length < 200); }) .AddRule("Firstname can't be the same as the lastname", delegate(object value) { bool isValid = true; string lastName = Knockout.UnwrapObservable <string>(self.LastName); if (lastName != null && (string)value == lastName) { isValid = false; } return isValid; } )); }