public PersonViewModel()
        {
            this.FirstName = Knockout.Observable("Matthew");
            this.LastName = Knockout.Observable("Leibowitz");
            this.FullName = Knockout.Computed(() => this.FirstName.Value + " " + this.LastName.Value);

            // AND, there is way to perform the updates to the computed object

            //var options = new DependentObservableOptions<string>();
            //options.GetValueFunction = () => self.FirstName.Value + " " + self.LastName.Value;
            //options.SetValueFunction = s =>
            //{
            //    s = s.Trim();
            //    var index = s.IndexOf(" ");
            //    if (index == -1)
            //    {
            //        self.FirstName.Value = s;
            //        self.LastName.Value = string.Empty;
            //    }
            //    else
            //    {
            //        self.FirstName.Value = s.Substring(0, index);
            //        self.LastName.Value = s.Substring(index + 1, s.Length);
            //    }
            //};
            //this.FullName = Knockout.Computed(options);
        }
        public ClickCounterViewModel()
        {
            var self = this;

            this.NumberOfClicks = Knockout.Observable(0);
            this.RegisterClick = () => self.NumberOfClicks.Value = self.NumberOfClicks.Value + 1;
            this.ResetClicks = () => self.NumberOfClicks.Value = 0;
            this.HasClickedTooManyTimes = Knockout.Computed(() => self.NumberOfClicks.Value >= 3);
        }
示例#3
0
        /// <summary>
        /// Creates a new view model.
        /// </summary>
        /// <param name="first">The initial first name.</param>
        /// <param name="last">The initial last name.</param>
        public ViewModel(string first, string last)
        {
            FirstName = ko.observable(first);
            LastName  = ko.observable(last);

            FullName = ko.computed(() =>
            {
                return(FirstName() + " " + LastName());
            }, this);
        }
示例#4
0
        /// <summary>
        /// Creates a new view model.
        /// </summary>
        /// <param name="first">The initial first name.</param>
        /// <param name="last">The initial last name.</param>
        public ViewModel(string first, string last)
        {
            FirstName = ko.observable(first);
            LastName = ko.observable(last);

            FullName = ko.computed(() =>
            {
                return FirstName() + " " + LastName();
            }, this);
        }
        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();

        }
示例#6
0
        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);
        }
示例#7
0
        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;
        }
示例#8
0
        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 StartStopSessionViewModel(Guid activityToStartStop, Guid sessionToStartStop)
        {
           
           
            // Create start session
            dev1_session newSession = new dev1_session();
            newSession.dev1_StartTime = DateTime.Now;
            StartSession = (Observable<SessionVM>)ValidatedObservableFactory.ValidatedObservable(new SessionVM(this, newSession));
           
            // Load the Sessions
            dev1_session session = (dev1_session)OrganizationServiceProxy.Retrieve(dev1_session.EntityLogicalName, "{FD722AC2-B234-E211-A471-000C299FFE7D}", new string[] { "AllColumns" });
            SessionVM sessionVM = new SessionVM(this, session);
            StopSession = (Observable<SessionVM>)ValidatedObservableFactory.ValidatedObservable(sessionVM);

            DependentObservableOptions<bool> isFormValidDependantProperty = new DependentObservableOptions<bool>();
            isFormValidDependantProperty.Model = this;
            
            isFormValidDependantProperty.GetValueFunction = new Func<bool>(delegate
            {
                StartStopSessionViewModel vm = (StartStopSessionViewModel)isFormValidDependantProperty.Model;
                
                if (vm.StartNewSession.GetValue())
                {
                    return ValidationRules.AreValid(
                       new object[] { ((StartStopSessionViewModel)isFormValidDependantProperty.Model).StopSession,
                       ((StartStopSessionViewModel)isFormValidDependantProperty.Model).StartSession });
                   
                }
                else
                {
                    
                    return ValidationRules.AreValid(
                       new object[] { ((StartStopSessionViewModel)isFormValidDependantProperty.Model).StopSession });
                    
                }

            });
            CanSave = Knockout.DependentObservable<bool>(isFormValidDependantProperty);

            
        }
示例#10
0
        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);
        }
示例#11
0
        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 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 StartStopSessionViewModel(Guid activityToStartStop, Guid sessionToStartStop)
        {
            // Create start session
            dev1_session newSession = new dev1_session();

            newSession.dev1_StartTime = DateTime.Now;
            StartSession = (Observable <SessionVM>)ValidatedObservableFactory.ValidatedObservable(new SessionVM(this, newSession));

            // Load the Sessions
            dev1_session session   = (dev1_session)OrganizationServiceProxy.Retrieve(dev1_session.EntityLogicalName, "{FD722AC2-B234-E211-A471-000C299FFE7D}", new string[] { "AllColumns" });
            SessionVM    sessionVM = new SessionVM(this, session);

            StopSession = (Observable <SessionVM>)ValidatedObservableFactory.ValidatedObservable(sessionVM);

            DependentObservableOptions <bool> isFormValidDependantProperty = new DependentObservableOptions <bool>();

            isFormValidDependantProperty.Model = this;

            isFormValidDependantProperty.GetValueFunction = new Func <bool>(delegate
            {
                StartStopSessionViewModel vm = (StartStopSessionViewModel)isFormValidDependantProperty.Model;

                if (vm.StartNewSession.GetValue())
                {
                    return(ValidationRules.AreValid(
                               new object[] { ((StartStopSessionViewModel)isFormValidDependantProperty.Model).StopSession,
                                              ((StartStopSessionViewModel)isFormValidDependantProperty.Model).StartSession }));
                }
                else
                {
                    return(ValidationRules.AreValid(
                               new object[] { ((StartStopSessionViewModel)isFormValidDependantProperty.Model).StopSession }));
                }
            });
            CanSave = Knockout.DependentObservable <bool>(isFormValidDependantProperty);
        }
示例#14
0
 public static void notifySubscribers <T>(this DependentObservable <T> observable, T value, string eventName = null)
 {
 }
        public TwitterViewModel(List<TweetGroup> lists, string selectedList)
        {
            var self = this;

            this.SavedLists = Knockout.ObservableArray(lists);
            this.EditingList = new TweetGroup(
                name: Knockout.Observable(selectedList),
                userNames: Knockout.ObservableArray<string>()
            );
            this.UserNameToAdd = Knockout.Observable("");
            this.CurrentTweets = Knockout.ObservableArray(new object[0]);
            this.FindSavedList = name => KnockoutUtils.ArrayFirst(self.SavedLists.Value, grp => grp.Name.Value == name, self);
            this.AddUser = () => {
                if (self.UserNameToAdd.Value != null && self.UserNameToAddIsValid.Value) {
                    self.EditingList.UserNames.Push(self.UserNameToAdd.Value);
                    self.UserNameToAdd.Value = "";
                }
            };
            this.RemoveUser = userName => self.EditingList.UserNames.Remove(userName);
            this.SaveChanges = new Action(OnSaveChanges);
            this.DeleteList = () => {
                var nameToDelete = self.EditingList.Name.Value;
                var savedListsExceptOneToDelete = self.SavedLists.Value.Filter(grp => grp.Name.Value != nameToDelete);
                self.EditingList.Name.Value =
                    savedListsExceptOneToDelete.Length == 0
                        ? null
                        : savedListsExceptOneToDelete[0].Name.Value;
                self.SavedLists.Value = savedListsExceptOneToDelete;
            };
            Knockout.Computed(() => {
                // Observe viewModel.editingList.name(), so when it changes
                // (i.e., user selects a different list) we know to copy the
                // saved list into the editing list
                var savedList = self.FindSavedList(self.EditingList.Name.Value);
                if (savedList != null) {
                    var userNamesCopy = savedList.UserNames.Slice(0);
                    self.EditingList.UserNames.Value = userNamesCopy;
                } else {
                    self.EditingList.UserNames.Value = new string[0];
                }
            });
            this.HasUnsavedChanges = Knockout.Computed(() => {
                if (self.EditingList.Name.Value == null) {
                    return self.EditingList.UserNames.Value.Length > 0;
                }
                var savedData = self.FindSavedList(self.EditingList.Name.Value).UserNames;
                var editingData = self.EditingList.UserNames.Value;
                return savedData.Value.Join("|") != editingData.Join("|");
            });
            this.UserNameToAddIsValid = Knockout.Computed(() => {
                    var pattern = @"^\s*[a-zA-Z0-9_]{1,15}\s*$";
                    return self.UserNameToAdd.Value == "" ||
                           self.UserNameToAdd.Value.Match(new Regex(pattern, "g")) != null;
                });
            this.CanAddUserName = Knockout.Computed(() => {
                return self.UserNameToAddIsValid.Value && self.UserNameToAdd.Value != "";
            });
            // The active user tweets are (asynchronously) computed from editingList.userNames
            Knockout.Computed(() => {
                TwitterApi.GetTweetsForUsers<object[]>(
                    self.EditingList.UserNames.Value,
                    result => {
                        self.CurrentTweets.Value = result;
                    });
            });
        }
示例#16
0
 public static void subscribe <T>(this DependentObservable <T> observable, Action <T> callback, object callbackTarget = null, string eventName = null)
 {
 }
        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 AnimatedTransitionsViewModel()
        {
            var self = this;

            Planets = Knockout.ObservableArray(new[]{
                new Planet( name: "Mercury", type: "rock"),
                new Planet( name: "Venus", type: "rock"),
                new Planet( name: "Earth", type: "rock"),
                new Planet( name: "Mars", type: "rock"),
                new Planet( name: "Jupiter", type: "gasgiant"),
                new Planet( name: "Saturn", type: "gasgiant"),
                new Planet( name: "Uranus", type: "gasgiant"),
                new Planet( name: "Neptune", type: "gasgiant"),
                new Planet( name: "Pluto", type: "rock")
            });

            TypeToShow = Knockout.Observable("all");
            DisplayAdvancedOptions = Knockout.Observable(false);
            AddPlanet = type => self.Planets.Push(new Planet("New planet", type));

            PlanetsToShow = Knockout.Computed(() =>
                {
                    // Represents a filtered list of planets
                    // i.e., only those matching the "typeToShow" condition
                    var desiredType = self.TypeToShow.Value;

                    if (desiredType == "all") return self.Planets.Value;
                    return KnockoutUtils.ArrayFilter(self.Planets.Value, planet => planet.Type == desiredType);
                });

            // Animation callbacks for the planets list
            ShowPlanetElement = elem => {
                if (elem.NodeType == ElementType.Element)
                    jQuery.FromElement(elem).Hide().SlideDown();
            };
            HidePlanetElement = elem => {
                if (elem.NodeType == ElementType.Element)
                    jQuery.FromElement(elem).SlideUp(EffectDuration.Slow, () => jQuery.FromElement(elem).Remove());
            };

            // Here's a custom Knockout binding that makes elements
            // shown/hidden via jQuery's fadeIn()/fadeOut() methods
            //Could be stored in a separate utility library
            Knockout.BindingHandlers["fadeVisible"] = new InlineBindingHandler<Observable<bool>>(
                init: (element, valueAccessor, allBindingsAccessor, model) => {
                    // Initially set the element to be instantly visible/hidden
                    // depending on the value
                    var value = valueAccessor.Invoke();

                    // Use "unwrapObservable" so we can handle values that may
                    // or may not be observable
                    jQuery.FromElement(element).Toggle(KnockoutUtils.UnwrapObservable(value));
                },
                update: (element, valueAccessor, allBindingsAccessor, model) => {
                    // Whenever the value subsequently changes, slowly fade the
                    // element in or out
                    var value = valueAccessor.Invoke();
                    if (KnockoutUtils.UnwrapObservable(value)) jQuery.FromElement(element).FadeIn();
                    else jQuery.FromElement(element).FadeOut();
                }
            );
        }
示例#19
0
 public static void extend <T>(this DependentObservable <T> observable, object extenders)
 {
 }
示例#20
0
 public static void dispose <T>(this DependentObservable <T> observable)
 {
 }
示例#21
0
 public static int getDependenciesCount <T>(this DependentObservable <T> observable)
 {
     return(0);
 }
示例#22
0
 public static int getSubscriptionsCount <T>(this DependentObservable <T> observable)
 {
     return(0);
 }